如何使用预准备语句在postgresql中插入带时区的时间戳?

Mik*_*asi 14 postgresql timestamp prepared-statement value-of timestamp-with-timezone

我正在尝试使用预准备语句将包含日期,时间和时区的字符串插入到我的数据库的时区字段的时间戳中.

问题是Timestamp.valueof函数没有考虑字符串包含的时区,因此它会导致错误.接受的格式是yyyy- [m] m- [d] d hh:mm:ss [.f ...],没有提到时区.

这是导致错误的确切代码:

pst.setTimestamp(2,Timestamp.valueOf("2012-08-24 14:00:00 +02:00"))

有什么方法可以克服它吗?提前致谢!

a_h*_*ame 5

基本问题是java.sql.Timestamp不包含时区信息。我认为始终假定它是“本地时区”。

在解决方案上,我可以想到的是不要在PreparedStatement中使用参数,而是在SQL中使用时区文字:

update foo
  set ts_col = timestamp with time zone '2012-08-24 14:00:00 +02:00'`;
Run Code Online (Sandbox Code Playgroud)

另一种可能的解决方案是将正确格式的字符串传递给使用to_timestamp()的PrepareStatement:

String sql = "update foo set ts_col = to_timestamp(?, 'yyyy-mm-dd hh24:mi:ss')"; 
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setString(1, "2012-08-24 14:00:00 +02:00");
Run Code Online (Sandbox Code Playgroud)


mar*_*k89 0

我相信您可以在数据库中再使用一个字段,其中包括时区。得到这两个字段后手动计算时间