Home > Database > Mysql Tutorial > How to Insert and Retrieve `java.time.LocalDate` Objects using JDBC?

How to Insert and Retrieve `java.time.LocalDate` Objects using JDBC?

Barbara Streisand
Release: 2025-01-22 01:37:08
Original
444 people have browsed it

How to Insert and Retrieve `java.time.LocalDate` Objects using JDBC?

Insert java.time.LocalDate objects into and retrieve

from SQL database using JDBC

Question:

How to handle java.time types such as LocalDate using JDBC (for SQL databases like H2)?

Answer:

There are two methods:

JDBC 4.2 compatible driver:

  • Insert data:

    <code class="language-java">  myPreparedStatement.setObject(1, myLocalDate); // 自动转换</code>
    Copy after login
  • Retrieve data:

    <code class="language-java">  LocalDate localDate = myResultSet.getObject("my_date_column_", LocalDate.class); // 预期返回类型</code>
    Copy after login

Incompatible driver (pre-JDBC 4.2):

  • Insert data: Use java.sql.Date.valueOf(myLocalDate) to convert LocalDate to java.sql.Date.
  • Retrieve data: Use sqlDate.toLocalDate() to convert java.sql.Date to LocalDate.

java.time Framework for Java 8:

  • Introduced new and improved datetime classes (such as LocalDate).
  • avoids problems with legacy classes (e.g. java.util.Date, Calendar).
  • Ability to exchange data directly with JDBC databases (when using a compatible driver).

Note: H2 supports JDBC 4.2, so you can use the easier compatibility method (first method).

The above is the detailed content of How to Insert and Retrieve `java.time.LocalDate` Objects using JDBC?. 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