JDBC Data Exchange with java.time Objects
Question: How can I include java.time types in my SQL database using JDBC, specifically H2 Database Engine?
Answer: There are two methods to orchestrate data exchange with java.time objects through JDBC:
JDBC 4.2 Compliant Drivers
Non-JDBC 4.2 Compliant Drivers
Example Code Using H2 Database
JDBC 4.2 Compliant
LocalDate today = LocalDate.now(ZoneId.of("America/Montreal")); // Insert row preparedStatement.setObject(1, today.minusDays(1)); preparedStatement.executeUpdate(); preparedStatement.setObject(1, today); preparedStatement.executeUpdate(); preparedStatement.setObject(1, today.plusDays(1)); preparedStatement.executeUpdate(); // Retrieve data LocalDate localDate = myResultSet.getObject("date_", LocalDate.class);
Non-JDBC 4.2 Compliant
// Insert row preparedStatement.setDate(1, java.sql.Date.valueOf(today)); preparedStatement.executeUpdate(); // Retrieve data java.sql.Date sqlDate = myResultSet.getDate("date_"); LocalDate localDate = sqlDate.toLocalDate();
The above is the detailed content of How to Handle java.time Objects with JDBC in H2 Database?. For more information, please follow other related articles on the PHP Chinese website!