Home > Java > javaTutorial > How to Handle java.time Objects with JDBC in H2 Database?

How to Handle java.time Objects with JDBC in H2 Database?

Mary-Kate Olsen
Release: 2024-12-31 19:02:11
Original
255 people have browsed it

How to Handle java.time Objects with JDBC in H2 Database?

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

  • With JDBC drivers compatible with JDBC 4.2 or higher, you can directly manipulate java.time objects.
  • The JDBC committee incorporated setObject/getObject methods to handle this, eliminating the need for setLocalDate/getLocalDate-like methods.
  • To insert data, use the setObject method with your java.time object as the argument.
  • For data retrieval, use the getObject method with the expected data type as an additional argument, ensuring type-safety.

Non-JDBC 4.2 Compliant Drivers

  • For JDBC drivers not yet compatible with JDBC 4.2, temporarily convert between java.time and java.sql types.
  • Use java.sql.Date.valueOf to convert LocalDate to java.sql.Date for insertion.
  • For retrieval, convert the retrieved java.sql.Date into LocalDate using its toLocalDate method.

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);
Copy after login

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();
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template