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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3