如何在 JDBC 中设置表中的时间?
jdbcjava 8object oriented programmingprogramming更新于 2024/9/18 1:16:17
您可以使用时间数据类型在 SQL 中插入时间值,java.sql.Time 类映射到 SQL 时间类型。
PreparedStatement 接口提供了一个名为 setTime() 的方法。使用该方法,您可以将时间插入表中。此方法接受两个参数 −
一个整数,表示我们需要设置日期值的占位符 (?) 的参数索引。
一个时间对象,表示要传递的时间值。 java.sql.Time 类的构造函数接受一个 long 类型的变量,该变量表示从纪元(标准基准时间,即 1970 年 1 月 1 日,00:00:00 GMT)开始的毫秒数。
示例
假设我们在 MySQL 数据库中创建了一个名为 Dispatches 的表,其描述如下 −
+------------------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +------------------+--------------+------+-----+---------+-------+ | Product_Name | varchar(255) | YES | | NULL | | | Date_Of_Dispatch | date | YES | | NULL | | | Time_Of_Dispatch | time | YES | | NULL | | | Location | varchar(255) | YES | | NULL | | +------------------+--------------+------+-----+---------+-------+
以下 JDBC 程序将记录插入到此表 −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Time;
import java.sql.Date;
public class InsertingTime {
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 Dispatches VALUES (?, ?, ?, ?)";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, "KeyBoard"); pstmt.setDate(2, new Date(1567296000000L));
pstmt.setTime(3, new Time(1567296000000L));
pstmt.setString(4, "Hyderabad");
pstmt.execute();
pstmt.setString(1, "Earphones"); pstmt.setDate(2, new Date(1556668800000L));
pstmt.setTime(3, new Time(1556668800000L));
pstmt.setString(4, "Vishakhapatnam");
pstmt.execute();
pstmt.setString(1, "Mouse"); pstmt.setDate(2, new Date(1551398399000L));
pstmt.setTime(3, new Time(1551398399000L));
pstmt.setString(4, "Vijayawada");
pstmt.execute();
System.out.println("Records inserted......");
}
}
输出
Connection established...... Records inserted......

