简体   繁体   English

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

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

When retrieving a java.sql.Timestamp from a database via JDBC 4.1 or earlier, how does one obtain/convert to a java.time object? 通过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。

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.Timestamp object for free. 通过在Java 8及更高版本中使用驱动程序,您应该自动在java.sql.Timestamp对象上自动java.sql.Timestamp一些方法。 Both java.sql.Time and java.sql.Date have similar conversion methods. java.sql.Timejava.sql.Date都有类似的转换方法。

Namely, to convert from java.sql to java.time you are looking for: 也就是说,要从java.sql转换为java.time,您正在寻找:

To go the other direction, from java.time to java.sql , use the new static methods: 要从另一个方向,从java.timejava.sql ,请使用新的静态方法:

Example: 例:

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

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. 正如其他人在评论中所说,PostgreSQL的JDBC驱动程序现在支持JDBC 4.2,包括Java 8 Time API支持。 We can exchange java.time objects directly with the database. 我们可以直接用数据库交换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. 所以不需要转换,也不需要再次使用java.sql类型。 Use only their replacements in the java.time package as shown in this list. 仅使用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.time object by calling PreparedStatement::setObject . 通过调用PreparedStatement::setObject存储java.time对象。

myPreparedStatement.setObject( … , myInstant ) ; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM