如何在 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