oracle jdbc中的PreparedStatement和setTimestamp

Posted

技术标签:

【中文标题】oracle jdbc中的PreparedStatement和setTimestamp【英文标题】:PreparedStatement and setTimestamp in oracle jdbc 【发布时间】:2011-02-20 22:32:16 【问题描述】:

我在 where 子句中使用带有时间戳的 PreparedStatement:

PreparedStatement s=c.prepareStatement("select value,utctimestamp from t where utctimestamp>=? and utctimestamp<?"); 
s.setTimestamp(1, new Timestamp(1273017600000L));   //2010-05-05 00:00 GMT
s.setTimestamp(2, new Timestamp(1273104000000L));   //2010-05-06 00:00 GMT
ResultSet rs = s.executeQuery();
if(rs.next()) System.out.println(rs.getInt("value"));

当我在客户端计算机上有不同的时区时,我得到的结果是不同的。这是 Oracle jdbc 中的错误吗?还是正确的行为?

Oracle 数据库版本为 10.2,我已尝试使用 oracle jdbc 瘦驱动程序版本 10.2 和 11.1。

参数是Timestamp,我预计途中不会进行时间转换。数据库列类型是 DATE,但我也用 TIMESTAMP 列类型进行了检查,结果相同。

有没有办法获得正确的结果?我无法将整个应用程序中的默认时区更改为 UTC。

感谢您的帮助

【问题讨论】:

请编辑您的问题并添加 t_begin 和 t_end 的类型。 【参考方案1】:

要在 UTC 时区的 PreparedStatement 中设置时间戳值,应该使用

stmt.setTimestamp(1, t, Calendar.getInstance(TimeZone.getTimeZone("UTC")))

Timestamp 值始终是 UTC,但 jdbc 驱动程序并不总是能够自动正确地将其发送到服务器。第三个,Calendar 参数,帮助驱动程序正确地为服务器准备值。

【讨论】:

其实就是:setTimestamp(int parameterIndex, Timestamp x, Calendar cal) 在我的环境中设置具有不同时区的日历对象会影响写入的 SQL 数据。

以上是关于oracle jdbc中的PreparedStatement和setTimestamp的主要内容,如果未能解决你的问题,请参考以下文章

JDBC-3(Transcation) ****

使用PreparedStatement接口实现增删改操作

sqlJdbcUtil.jjava

SqlserverMysqlOracle各自的默认端口号

MySQL使用中遇到的error

springboot连接oracle数据库注意事项