Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the date from a ResultSet for use with java.time classes

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.

like image 355
Thomas Paulin Avatar asked Apr 21 '15 13:04

Thomas Paulin


People also ask

How do you find the ResultSet of a date?

Execute the query using the executeQuery() method. Pass the select query to retrieve data (String) as a parameter to it. From the obtained result set object get the date value (along with other values) using the getDate() method of the ResultSet interface. Pass the name of the column (String) as a parameter to this.

Which method is used to read the data from ResultSet?

To read data using the ResultSet 's methods (e.g. getString() , getInt() , getFloat() , etc) we can either use the column name, or the column index of the field read in the SQL statement.

Can ResultSet be reused?

If you want to test, whether your resultset gets closed or not, you can use a while loop to iterate over the result set and inside the while loop, create another query and assign it to same result set. You will see that an Exception will be thrown..

What does ResultSet return in Java?

Return value This method returns a boolean value specifying whether the ResultSet object contains more rows. If there are no rows next to its current position this method returns false, else it returns true.


1 Answers

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.

like image 89
Meno Hochschild Avatar answered Sep 27 '22 21:09

Meno Hochschild