Java oracle jdbc 中的 PreparedStatement 和 setTimestamp

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2858182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:46:32  来源:igfitidea点击:

PreparedStatement and setTimestamp in oracle jdbc

javaoraclejdbctimestampprepared-statement

提问by Roman

I am using PreparedStatement with Timestamp in where clause:

我在 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"));

The result I get is different, when I have different time zones on the client computer. Is this a bug in Oracle jdbc? or correct behavior?

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

Oracle database version is 10.2 and I have tried with oracle jdbc thin driver version 10.2 and 11.1.

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

The parameter is Timestamp, and I expected that no time conversions will be done on the way. The database column type is DATE, but I also checked it with TIMESTAMP column type with the same results.

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

Is there a way to achieve correct result? I cannot change default timezone in the the whole application to UTC.

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

Thanks for your help

谢谢你的帮助

采纳答案by Roman

To set a timestamp value in a PreparedStatement in UTC timezone one should use

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

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

The Timestamp value is always UTC, but not always the jdbc driver can automatically sent it correctly to the server. The third, Calendar, parameter helps the driver to correctly prepare the value for the server.

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