JDBC中使用Java8的日期LocalDate和LocalDateTime操作mysql、postgresql
前言
相信大家應(yīng)該都知道,在實(shí)體Entity里面,可以使用java.sql.Date、java.sql.Timestamp、java.util.Date來映射到數(shù)據(jù)庫(kù)的date、timestamp、datetime等字段
但是,java.sql.Date、java.sql.Timestamp、java.util.Date這些類都不好用,很多方法都過時(shí)了。
Java8里面新出來了一些API,LocalDate、LocalTime、LocalDateTime 非常好用
如果想要在JDBC中,使用Java8的日期LocalDate、LocalDateTime,則必須要求數(shù)據(jù)庫(kù)驅(qū)動(dòng)的版本不能低于4.2
下面將分別演示如何在JDBC中使用Java8的日期LocalDate、LocalDateTime來操作mysql,postgresql,話不多說了,來一看看詳細(xì)的介紹吧。
一:MySQL
首先創(chuàng)建表:
create table tb_java8date (id int not null primary key auto_increment,t_date date, t_time time, t_datetime datetime);
然后,加入mysql的驅(qū)動(dòng)
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.37</version> </dependency>
上面說了,數(shù)據(jù)庫(kù)驅(qū)動(dòng)的版本不能低于4.2,如何判斷呢?
直接打開數(shù)據(jù)庫(kù)驅(qū)動(dòng)jar,里面有個(gè)META-INF/MANIFEST.MF文件

注意這里,必須要至少是4.2
JDBC代碼如下:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class App {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://192.168.1.100:3306/db_java8","root","root123");
PreparedStatement st = conn.prepareStatement("insert into tb_java8date (t_date,t_time,t_datetime)values(?,?,?)");
st.setObject(1, LocalDate.now());
st.setObject(2, LocalTime.now());
st.setObject(3, LocalDateTime.now());
st.execute();
st.close();
conn.close();
}
}
運(yùn)行,查詢數(shù)據(jù)庫(kù)
mysql> select * from tb_java8date; +----+------------+----------+---------------------+ | id | t_date | t_time | t_datetime | +----+------------+----------+---------------------+ | 1 | 2016-11-13 | 11:34:31 | 2016-11-13 11:34:31 | +----+------------+----------+---------------------+ 1 row in set (0.00 sec)
看到已經(jīng)成功插入到數(shù)據(jù)庫(kù)中去了
如果你使用的mysql-connector-java版本低于5.1.37,則數(shù)據(jù)庫(kù)的驅(qū)動(dòng)版本低于4.2,運(yùn)行會(huì)報(bào)如下錯(cuò)誤:
Exception in thread "main" com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect date value: '\xAC\xED\x00\x05sr\x00\x0Djava.time.Ser\x95]\x84\xBA\x1B"H\xB2\x0C\x00\x00xpw\x07\x03\x00\x00\x07\xE0\x0B\x0Dx' for column 't_date' at row 1 at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3845) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3783) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2447) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2594) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2545) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1901) at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1193) at com.pp.App.main(App.java:18)
二:PostgreSQL
首先創(chuàng)建表:
create table tb_java8date (id SERIAL not null primary key,t_date date, t_time time, t_datetime timestamp);
然后,加入PostgreSQL的數(shù)據(jù)庫(kù)驅(qū)動(dòng)
<dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>9.4.1212</version> </dependency>
注意這里添加的數(shù)據(jù)庫(kù)驅(qū)動(dòng)版本最低要是4.2,檢驗(yàn)方法和上面類似

JDBC代碼如下:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class App {
public static void main( String[] args ) throws Exception {
Class.forName("org.postgresql.Driver");
Connection conn = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/pg_java8","admin","123456");
PreparedStatement st = conn.prepareStatement("insert into tb_java8date (t_date,t_time,t_datetime)values(?,?,?)");
System.out.println(st.getClass());
st.setObject(1, LocalDate.now());
st.setObject(2, LocalTime.now());
st.setObject(3, LocalDateTime.now());
st.execute();
st.close();
conn.close();
}
}
運(yùn)行,然后查詢數(shù)據(jù)庫(kù)表

發(fā)現(xiàn),已經(jīng)成功執(zhí)行
如果你加入的依賴,數(shù)據(jù)庫(kù)的驅(qū)動(dòng)版本低于4.2,運(yùn)行會(huì)報(bào)如下錯(cuò)誤:
Exception in thread "main" org.postgresql.util.PSQLException: Can't infer the SQL type to use for an instance of java.time.LocalDate. Use setObject() with an explicit Types value to specify the type to use. at org.postgresql.jdbc.PgPreparedStatement.setObject(PgPreparedStatement.java:1051) at com.pp.App.main(App2.java:16)
以上只是演示了mysql,postgresql兩個(gè)數(shù)據(jù)庫(kù),其他的數(shù)據(jù)庫(kù),請(qǐng)自行測(cè)試。我這里就不演示了,方法都類似。
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
SpringBoot+MybatisPlus實(shí)現(xiàn)sharding-jdbc分庫(kù)分表的示例代碼
本文主要介紹了SpringBoot+MybatisPlus實(shí)現(xiàn)sharding-jdbc分庫(kù)分表的示例代碼,以分庫(kù),分表,分庫(kù)分表三種方式來實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下2024-03-03
Java線程池中的Future實(shí)現(xiàn)詳解
這篇文章主要介紹了Java線程池中的Future實(shí)現(xiàn)詳解, FutureTask是一個(gè)任務(wù),FutureTask繼承了Runnable、Callable, 通過FutureTask可以獲取到任務(wù)執(zhí)行的狀態(tài),任務(wù)執(zhí)行完成完成后,將結(jié)構(gòu)通過Future接口返回,調(diào)用者可以調(diào)用Future#get()方法獲取到數(shù)據(jù),需要的朋友可以參考下2023-10-10
Java調(diào)用DeepSeek?api實(shí)現(xiàn)方法記錄
這篇文章主要介紹了如何在Java中調(diào)用DeepSeek?API,包括在官網(wǎng)獲取APIKeys、創(chuàng)建API請(qǐng)求工具類以及處理返回結(jié)果的步驟,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2025-02-02
Java 中Json中既有對(duì)象又有數(shù)組的參數(shù)如何轉(zhuǎn)化成對(duì)象(推薦)
Gson庫(kù)是一個(gè)功能強(qiáng)大、易于使用的Java序列化/反序列化庫(kù),它提供了豐富的API來支持Java對(duì)象和JSON之間的轉(zhuǎn)換,這篇文章主要介紹了Java 中Json中既有對(duì)象又有數(shù)組的參數(shù)如何轉(zhuǎn)化成對(duì)象,需要的朋友可以參考下2024-07-07

