SQL中的时间戳数据类型与日期(SQL中)相似,都存储日期:月:年:小时:分钟:秒。除了此时间戳之外,它还存储小数秒。
PreparedStatement接口提供了一个名为的方法的setTimestamp()标准碱此方法接受两个参数表示在其中需要存储的时间戳和表示从 信号出现时间的毫秒数长可变的地方保持器的参数索引的整数变量(时间,即1970年1月1日,格林尼治标准时间00:00:00)。
假设我们在数据库中有一个名为dispatchs的表,具有以下描述-
+------------------+--------------+------+-----+-------------------+ | Field | Type | Null | Key | Default | +------------------+--------------+------+-----+-------------------+ | Product_Name | varchar(100) | YES | | NULL | | Name_Of_Customer | varchar(100) | YES | | NULL | | Time_Of_Dispatch | timestamp | NO | | CURRENT_TIMESTAMP | | Location | varchar(100) | YES | | NULL | +------------------+--------------+------+-----+-------------------+
如您所见,该表包含名为Time_Of_Dispatch的列,该列存储时间戳记值。
我们可以使用PreparedStatement接口的setTimestamp()方法将时间戳存储在其中,并使用ResultSet接口的getTimestamp()方法进行检索。
以下JDBC程序将记录存储到调度表中并检索它们-
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.sql.Timestamp; public class TimeStampExample { public static void main(String args[])throws Exception { //获得连接 String mysqlUrl = "jdbc:mysql://localhost/sampledb"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //将值插入表 String query = "INSERT INTO Dispatches VALUES (?, ?, ?, ?)"; PreparedStatement pstmt = con.prepareStatement(query); pstmt.setString(1, "KeyBoard"); pstmt.setString(2, "Amith"); pstmt.setTimestamp(3, new Timestamp(1567296000000L)); pstmt.setString(4, "Hyderabad"); pstmt.execute(); pstmt.setString(1, "Earphones"); pstmt.setString(2, "Sumith"); pstmt.setTimestamp(3, new Timestamp(1556668800000L)); pstmt.setString(4, "Vishakhapatnam"); pstmt.execute(); pstmt.setString(1, "Mouse"); pstmt.setString(2, "Sudha"); pstmt.setTimestamp(3, new Timestamp(1551398399000L)); pstmt.setString(4, "Vijayawada"); pstmt.execute(); System.out.println("Records inserted......"); //创建Statement对象 Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select * from Dispatches"); //检索值 while(rs.next()) { System.out.println("Product Name: "+rs.getString("Product_Name")); System.out.println("Name Of The Customer: "+rs.getString("Name_Of_Customer")); System.out.println("Time Of Dispatch: "+rs.getTimestamp("Time_Of_Dispatch")); System.out.println("Location: "+rs.getString("Location")); System.out.println(); } } }
输出结果
Connection established...... Records inserted...... Product Name: KeyBoard Name Of The Customer: Amith Time Of Dispatch: 2019-09-01 05:30:00.0 Location: Hyderabad Product Name: Earphones Name Of The Customer: Sumith Time Of Dispatch: 2019-05-01 05:30:00.0 Location: Vishakhapatnam Product Name: Mouse Name Of The Customer: Sudha Time Of Dispatch: 2019-03-01 05:29:59.0 Location: Vijayawada