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

人走茶凉 提交于 2019-11-27 19:42:00
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.Timestamp object for free. Both java.sql.Time and java.sql.Date have similar conversion methods.

Namely, to convert from java.sql to java.time you are looking for:

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

Example:

preparedStatement.setTimestamp( 2, Timestamp.from(instant) );
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.time objects directly with the database.

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.time package as shown in this list.

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 rs = ...;
while (rs.next()) {
  LocalDate localDate = rs.getObject(1, LocalDate.class));
}

Store a java.time object by calling PreparedStatement::setObject.

myPreparedStatement.setObject( … , myInstant ) ; 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!