简体   繁体   中英

Is it better to use ResultSet.getString() or ResultSet.getTimestamp() to get a timestamp?

In retrieving a timestamp from Postgres or Oracle -- let's call it startDate -- is it better to use the resultSet.getString("startDate") call or resultSet.getTimestamp("startDate") ?

Currently I'm using resultSet.getString("startDate") and it works fine, but it occurred to me it might be better practice to use getTimestamp() .

Is there an established best practice? Could there be any unexpected consequences from using ResultSet.getString() on a timestamp?

Is it better to use ResultSet.getString() or ResultSet.getTimestamp() to get a timestamp?

Neither.

It's better to get a date-time object than a string since this better represents what the thing is and means, and should lend itself better to further operations in the Java program.

At the same time it's far better to use the modern date-time classes from java.time than the old-fashioned Timestamp class. The latter has considerable design problems and has long been considered obsolete.

JDBC drivers are a little different, but see if you can get the correct time as either an Instant , an OffsetDateTime or if all else fails, then a LocalDateTime from your result set. In all cases use the two-argument getObject method. For example:

Instant instant = resultSet.getObject("startDate", Instant.class);

JDBC 4.2 specifies that java.time classes should be supported in this way. I believe all current SQL database engines have JDBC 4.2 compliant drivers out.

Only if you cannot use Java 8 or later, get a Timestamp as in your code. Next use the versions of the java.time classes from ThreeTen-Backport and use the DateTimeUtils class from ThreeTen-Backport for converting your Timestamp , best to en Instant , but if that happens to give you the wrong instant because of time zone trouble, then an LocalDateTime . Example:

Instant instant = 
    DateTimeUtils.toInstant(
        resultSet.getTimestamp("startDate")
    )
;

I would use resultSet.getTimestamp(). Then your data type is mapped properly from the code to the database. You can convert that result into a String if you wish then. I don't think there is a time cost of calling resultSet.getString(), but generally it's more appropriate to retrieve the correct data type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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