您可以使用日期資料類型在 SQL 中插入日期值,java.sql.Date 類別對應到 SQL DATE 類型。
The PreparedStatement 介面提供了一個名為setDate() 的方法。使用它您可以將日期插入表中。此方法接受兩個參數 -
一個整數,表示我們需要設定日期值的佔位符 (?) 的參數索引。
+----------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------+--------------+------+-----+---------+-------+ | Name | varchar(255) | YES | | NULL | | | DOB | date | YES | | NULL | | | Location | varchar(255) | YES | | NULL | | +----------+--------------+------+-----+---------+-------+
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.sql.Date; public class InsertingDate { public static void main(String args[])throws Exception { //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/sampleDB"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Inserting values to a table String query = "INSERT INTO Emp(Name, DOB, Location) VALUES (?, ?, ?)"; PreparedStatement pstmt = con.prepareStatement(query); pstmt.setString(1, "Amit"); pstmt.setDate(2, new Date(622790105000L)); pstmt.setString(3, "Hyderabad"); pstmt.execute(); pstmt.setString(1, "Sumith"); pstmt.setDate(2, new Date(620611200000L)); pstmt.setString(3, "Vishakhapatnam"); pstmt.execute(); pstmt.setString(1, "Sudha"); pstmt.setDate(2, new Date(336614400000L)); pstmt.setString(3, "Vijayawada"); pstmt.execute(); System.out.println("Records inserted......"); } }
Connection established...... Records inserted......
mysql> select * from Emp; +--------+------------+----------------+ | Name | DOB | Location | +--------+------------+----------------+ | Amit | 1989-09-26 | Hyderabad | | Sumith | 2019-03-19 | Vishakhapatnam | | Sudha | 2019-03-19 | Vijayawada | +--------+------------+----------------+ 3 rows in set (0.00 sec)
以上是JDBC中如何處理日期?的詳細內容。更多資訊請關注PHP中文網其他相關文章!