Question: How to handle java.time types like LocalDate via JDBC with an SQL database, such as H2?
Legacy Approach: Using PreparedStatement::setDate and ResultSet::getDate works for the outdated java.sql.Date type. However, it's preferable to avoid these problematic legacy classes.
Modern Approach: There are two main routes:
Example of Using JDBC 4.2 Compliant Driver:
// Insert LocalDate as SQL DATE preparedStatement.setObject(1, myLocalDate); // Retrieve LocalDate from SQL DATE LocalDate localDate = myResultSet.getObject("my_date_column", LocalDate.class);
Example of Using Non-Compliant Driver:
// Convert LocalDate to java.sql.Date for insertion java.sql.Date mySqlDate = java.sql.Date.valueOf(myLocalDate); preparedStatement.setDate(1, mySqlDate); // Convert java.sql.Date to LocalDate after retrieval LocalDate localDate = mySqlDate.toLocalDate();
Recommendation: Use the JDBC 4.2 compliant approach whenever possible. It's simpler and type-safe. However, the non-compliant method can still be used for drivers that don't support JDBC 4.2.
The above is the detailed content of How to Insert and Retrieve java.time.LocalDate Objects in JDBC Databases?. For more information, please follow other related articles on the PHP Chinese website!