search
HomeDatabaseMysql TutorialHow to Insert and Retrieve `java.time.LocalDate` Objects in an H2 Database Using JDBC?

How to Insert and Retrieve `java.time.LocalDate` Objects in an H2 Database Using JDBC?

Use JDBC to insert and retrieve java.time.LocalDate objects in SQL databases such as H2 database

Question:

How to insert and retrieve java.time types (e.g. LocalDate) in a SQL database like H2 database engine using JDBC?

Answer:

Method 1: Driver compatible with JDBC 4.2

For JDBC drivers compliant with the JDBC 4.2 specification or higher, you can directly use the setObject and getObject methods to handle java.time objects. The driver automatically detects Java types and converts them to corresponding SQL types. For example:

preparedStatement.setObject(1, myLocalDate); // LocalDate转换为SQL DATE
LocalDate localDate = myResultSet.getObject("my_date_column_", LocalDate.class); // 指定预期类以确保类型安全

Method 2: Old version driver before JDBC 4.2

For drivers that are not JDBC 4.2 compliant, you must briefly convert a java.time object to an equivalent java.sql type and vice versa. Use the conversion method added to the legacy class:

java.sql.Date mySqlDate = java.sql.Date.valueOf(myLocalDate);
preparedStatement.setDate(1, mySqlDate);
java.sql.Date sqlDate = myResultSet.getDate("date_"); //尽可能简短地处理转换
LocalDate localDate = sqlDate.toLocalDate();

JDBC 4.2 compatible driver example:

import java.sql.*;
import java.time.LocalDate;
import java.time.ZoneId;

public class LocalDateExample {

    public static void main(String[] args) throws SQLException {
        String url = "jdbc:h2:mem:test_db"; // 更改为您的数据库URL
        String user = "user";
        String password = "password";

        try (
                Connection conn = DriverManager.getConnection(url, user, password);
                Statement stmt = conn.createStatement();
        ) {
            stmt.execute("CREATE TABLE IF NOT EXISTS employees (id INT PRIMARY KEY, name VARCHAR(255), birthday DATE)");

            // 插入LocalDate值
            LocalDate today = LocalDate.now(ZoneId.of("America/Montreal"));

            PreparedStatement pstmt = conn.prepareStatement("INSERT INTO employees (name, birthday) VALUES (?, ?)");
            pstmt.setString(1, "John Doe");
            pstmt.setObject(2, today); // 直接传递LocalDate
            pstmt.executeUpdate();

            // 检索LocalDate值
            ResultSet rs = stmt.executeQuery("SELECT * FROM employees");
            while (rs.next()) {
                LocalDate birthday = rs.getObject("birthday", LocalDate.class); // 指定预期类
                System.out.println("员工:" + rs.getString("name") + ",生日:" + birthday);
            }

            rs.close();
            pstmt.close();
            stmt.close();
        }
    }
}

Legacy driver example:

import java.sql.*;
import java.time.LocalDate;

public class LocalDateExample {

    public static void main(String[] args) throws SQLException {
        String url = "jdbc:h2:mem:test_db"; // 更改为您的数据库URL
        String user = "user";
        String password = "password";

        try (
                Connection conn = DriverManager.getConnection(url, user, password);
                Statement stmt = conn.createStatement();
        ) {
            stmt.execute("CREATE TABLE IF NOT EXISTS employees (id INT PRIMARY KEY, name VARCHAR(255), birthday DATE)");

            // 插入LocalDate值
            LocalDate today = LocalDate.now();
            java.sql.Date sqlDate = java.sql.Date.valueOf(today);

            PreparedStatement pstmt = conn.prepareStatement("INSERT INTO employees (name, birthday) VALUES (?, ?)");
            pstmt.setString(1, "John Doe");
            pstmt.setDate(2, sqlDate); // 将LocalDate转换为java.sql.Date
            pstmt.executeUpdate();

            // 检索LocalDate值
            ResultSet rs = stmt.executeQuery("SELECT * FROM employees");
            while (rs.next()) {
                java.sql.Date sqlDate = rs.getDate("birthday");
                LocalDate birthday = sqlDate.toLocalDate(); // 将java.sql.Date转换为LocalDate
                System.out.println("员工:" + rs.getString("name") + ",生日:" + birthday);
            }

            rs.close();
            pstmt.close();
            stmt.close();
        }
    }
}

The above is the detailed content of How to Insert and Retrieve `java.time.LocalDate` Objects in an H2 Database Using JDBC?. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
How does MySQL handle data replication?How does MySQL handle data replication?Apr 28, 2025 am 12:25 AM

MySQL processes data replication through three modes: asynchronous, semi-synchronous and group replication. 1) Asynchronous replication performance is high but data may be lost. 2) Semi-synchronous replication improves data security but increases latency. 3) Group replication supports multi-master replication and failover, suitable for high availability requirements.

How can you use the EXPLAIN statement to analyze query performance?How can you use the EXPLAIN statement to analyze query performance?Apr 28, 2025 am 12:24 AM

The EXPLAIN statement can be used to analyze and improve SQL query performance. 1. Execute the EXPLAIN statement to view the query plan. 2. Analyze the output results, pay attention to access type, index usage and JOIN order. 3. Create or adjust indexes based on the analysis results, optimize JOIN operations, and avoid full table scanning to improve query efficiency.

How do you back up and restore a MySQL database?How do you back up and restore a MySQL database?Apr 28, 2025 am 12:23 AM

Using mysqldump for logical backup and MySQLEnterpriseBackup for hot backup are effective ways to back up MySQL databases. 1. Use mysqldump to back up the database: mysqldump-uroot-pmydatabase>mydatabase_backup.sql. 2. Use MySQLEnterpriseBackup for hot backup: mysqlbackup--user=root-password=password--backup-dir=/path/to/backupbackup. When recovering, use the corresponding life

What are some common causes of slow queries in MySQL?What are some common causes of slow queries in MySQL?Apr 28, 2025 am 12:18 AM

The main reasons for slow MySQL query include missing or improper use of indexes, query complexity, excessive data volume and insufficient hardware resources. Optimization suggestions include: 1. Create appropriate indexes; 2. Optimize query statements; 3. Use table partitioning technology; 4. Appropriately upgrade hardware.

What are views in MySQL?What are views in MySQL?Apr 28, 2025 am 12:04 AM

MySQL view is a virtual table based on SQL query results and does not store data. 1) Views simplify complex queries, 2) Enhance data security, and 3) Maintain data consistency. Views are stored queries in databases that can be used like tables, but data is generated dynamically.

What are the differences in syntax between MySQL and other SQL dialects?What are the differences in syntax between MySQL and other SQL dialects?Apr 27, 2025 am 12:26 AM

MySQLdiffersfromotherSQLdialectsinsyntaxforLIMIT,auto-increment,stringcomparison,subqueries,andperformanceanalysis.1)MySQLusesLIMIT,whileSQLServerusesTOPandOracleusesROWNUM.2)MySQL'sAUTO_INCREMENTcontrastswithPostgreSQL'sSERIALandOracle'ssequenceandt

What is MySQL partitioning?What is MySQL partitioning?Apr 27, 2025 am 12:23 AM

MySQL partitioning improves performance and simplifies maintenance. 1) Divide large tables into small pieces by specific criteria (such as date ranges), 2) physically divide data into independent files, 3) MySQL can focus on related partitions when querying, 4) Query optimizer can skip unrelated partitions, 5) Choosing the right partition strategy and maintaining it regularly is key.

How do you grant and revoke privileges in MySQL?How do you grant and revoke privileges in MySQL?Apr 27, 2025 am 12:21 AM

How to grant and revoke permissions in MySQL? 1. Use the GRANT statement to grant permissions, such as GRANTALLPRIVILEGESONdatabase_name.TO'username'@'host'; 2. Use the REVOKE statement to revoke permissions, such as REVOKEALLPRIVILEGESONdatabase_name.FROM'username'@'host' to ensure timely communication of permission changes.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool