如何在 JDBC 中设置表中的时间?
可以使用 time 数据类型在 SQL 中插入时间值,java.sql.Time 类映射到 SQL Time 类型。
PreparedStatement 接口提供了一个名为 setTime() 的方法。使用它可以将时间插入表中。此方法接受两个参数 -
表示参数索引的整数,占位符 (?) 表示我们需要设置日期值的位置。
表示要传递的时间值的 Time 对象。java.sql.Time 类的构造函数接受 long 类型变量,该变量表示距纪元(标准基准时间,即格林威治标准时间 1970 年 1 月 1 日 00:00:00)的毫秒数。
示例
假设我们在 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:///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......
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP