如何在没有 JDBC 4.2 驱动程序的情况下从 java.sql.Timestamp 获取 java.time 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22470150/
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 15:56:36  来源:igfitidea点击:

How to get a java.time object from a java.sql.Timestamp without a JDBC 4.2 driver?

javadatetimejdbcjava-time

提问by Basil Bourque

When retrieving a java.sql.Timestampfrom a database via JDBC 4.1 or earlier, how does one obtain/convert to a java.timeobject?

当通过 JDBC 4.1 或更早版本从数据库中检索java.sql.Timestamp 时,如何获取/转换为java.time对象?

Neither of the open-source JDBC drivers for Postgres is JDBC 4.2 compliant yet, so I'm looking for a way to use use java.time with JDBC 4.1.

Postgres 的开源 JDBC 驱动程序都不是 JDBC 4.2 兼容的,所以我正在寻找一种将 java.time 与 JDBC 4.1 一起使用的方法。

采纳答案by pickypg

New Methods On Old Classes

旧类的新方法

By using the driver with Java 8 and later, you should automatically pick up some methods on your java.sql.Timestampobject for free. Both java.sql.Timeand java.sql.Datehave similar conversion methods.

通过在 Java 8 及更高版本中使用驱动程序,您应该会自动java.sql.Timestamp免费获取对象上的一些方法。双方java.sql.Timejava.sql.Date有相似的转换方法。

Namely, to convert from java.sqlto java.timeyou are looking for:

即,要从java.sql转换为您正在寻找的java.time

To go the other direction, from java.timeto java.sql, use the new static methods:

转到另一个方向,从java.timejava.sql,使用新的静态方法:

Example:

例子:

preparedStatement.setTimestamp( 2, Timestamp.from(instant) );

回答by skrueger

No need to convert

无需转换

Like others have said in comments, PostgreSQL's JDBC driver now supports JDBC 4.2 including Java 8 Time API support. We can exchange java.timeobjects directly with the database.

就像其他人在评论中所说的那样,PostgreSQL 的 JDBC 驱动程序现在支持 JDBC 4.2,包括 Java 8 Time API 支持。我们可以直接与数据库交换java.time对象。

https://jdbc.postgresql.org/documentation/head/8-date-time.html

https://jdbc.postgresql.org/documentation/head/8-date-time.html

So no need to convert, no need to ever use the java.sql types again. Use only their replacements in the java.timepackage as shown in this list.

所以不需要转换,不需要再次使用 java.sql 类型。仅在java.time包中使用它们的替代品,如此列表中所示。

PostgreSQL?                      Java SE 8 (java.time)
DATE                             LocalDate
TIME [ WITHOUT TIMEZONE ]        LocalTime
TIMESTAMP [ WITHOUT TIMEZONE ]   LocalDateTime
TIMESTAMP WITH TIMEZONE          OffsetDateTime or Instant

This can be retrieved via ResultSet::getObject

这可以通过检索 ResultSet::getObject

ResultSet rs = ...;
while (rs.next()) {
  LocalDate localDate = rs.getObject(1, LocalDate.class));
}

Store a java.timeobject by calling PreparedStatement::setObject.

通过调用存储java.time对象PreparedStatement::setObject

myPreparedStatement.setObject( … , myInstant ) ;