postgresql jdbc date
时间: 2023-07-07 15:45:14 浏览: 70
可以使用以下代码来获取 PostgreSQL 数据库中的日期(date)类型的值:
```
import java.sql.*;
import java.util.Date;
public class Example {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
// 加载驱动类
Class.forName("org.postgresql.Driver");
// 连接数据库
conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/mydb", "username", "password");
// 创建 PreparedStatement 对象
pstmt = conn.prepareStatement("SELECT mydate FROM mytable WHERE id = ?");
pstmt.setInt(1, 1);
// 执行查询操作
rs = pstmt.executeQuery();
// 处理查询结果
while (rs.next()) {
Date mydate = rs.getDate("mydate");
System.out.println(mydate);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭资源
try {
if (rs != null) rs.close();
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
```
在上面的代码中,我们使用 `rs.getDate("mydate")` 方法获取查询结果集中名称为 `"mydate"` 的列的值,并将其转换为 `java.util.Date` 类型的对象。注意,如果查询结果集中的值为 `null`,则 `rs.getDate()` 方法返回 `null`。