Getting the date from a ResultSet for use with jav

2019-01-17 21:51发布

Is there anyway to get a java.time (new in Java 8) compatible time class out of a ResultSet?

I am aware you can use ResultSet's getDate or getTimestamp but these method return java.sql.Date / java.sql.Timestamp objects which are now deprecated so it seems like bad practice to use them in order to create a ZonedDateTime or similar.

2条回答
叼着烟拽天下
2楼-- · 2019-01-17 22:18

Most database vendors don't support JDBC 4.2 yet. This specification says that the new java.time-types like LocalDate will/should be supported using the existing methods setObject(...) and getObject(). No explicit conversion is required and offered (no API-change).

A workaround for the missing support can be manual conversion as described on the Derby-mailing list.

Something like:

LocalDate birthDate = resultSet.getDate("birth_date").toLocalDate();

As you can see, these conversions use the non-deprecated types java.sql.Date etc., see also the javadoc.

查看更多
男人必须洒脱
3楼-- · 2019-01-17 22:27

New Methods On Timestamp

Java 8 includes new methods on the java.sql.Timestamp class to convert to and from java.time objects. These convenience methods are a stop-gap measure until JDBC drivers can be updated for the new data types.

Ditto For Date & Time

The java.sql.Date and java.sql.Time classes have similar java.time conversion methods added in Java 8 as well.

查看更多
登录 后发表回答