如何使用 JDBC 在数据库中插入当前日期和时间?


MySQL 数据库中的 timestamp 数据类型存储日期、月份、年份、小时、分钟、秒和分数秒。使用它,您可以同时表示日期和时间。

在使用 JDBC 时,有两种方法可以插入/获取当前时间戳值。

  • 使用数据库的日期默认值。

  • 使用日历类的 getTime() 方法。

数据库默认值

创建一个名为 sample 的表,以使用以下查询在 MySQL 数据库中存储时间戳

CREATE TABLE Sample(Id INT, Current_Time_Stamp TimeStamp);

现在,如下所示描述表

+--------------------+-----------+------+-----+-------------------+
| Field              | Type      | Null | Key | Default           |
+--------------------+-----------+------+-----+-------------------+
| Id                 | int(11)   | YES  |     | NULL              |
| Current_Time_Stamp | timestamp | NO   |     | CURRENT_TIMESTAMP |
+--------------------+-----------+------+-----+-------------------+

如果您观察到,时间戳的默认值为系统当前时间戳。也就是说,如果您不向此列传递任何值,则默认情况下它将填充当前时间戳值。

因此,在使用 JDBC 程序将值插入具有时间戳的表时,在 Prepared 语句中保留时间戳列,或者简单地使用 CURRENT_TIMESTAMP 代替占位符 ?,这将填充当前时间戳值。

示例

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class InsertingCurrentTime {
   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 sample(ID, Current_Time_Stamp)
      VALUES (?, CURRENT_TIMESTAMP)";

      PreparedStatement pstmt = con.prepareStatement(query);
      pstmt.setInt(1, 1);
      pstmt.execute();
      System.out.println("Data inserted......");
   }
}

输出

Data inserted......

如果您观察表的內容,您可以看到它包含当前时间戳值,如下所示

+------+---------------------+
| Id   | Current_Time_Stamp  |
+------+---------------------+
| 1    | 2019-02-27 17:18:17 |
+------+---------------------+

Calendar 类的 getTime() 方法

Calendar 类的 getTime() 方法返回一个 Date 类的对象,该对象保存日历的当前时间值。

Calendar calendar = Calendar.getInstance();
java.util.Date currentTime = calendar.getTime();

java.util.Date 类还提供了一个名为 getTime() 的方法,此方法返回一个 long 类型变量,该变量表示从标准纪元时间(自 1970 年 1 月 1 日 00:00:00 GMT 起)到此对象的当前时间值的毫秒数。

long time = currentTime.getTime();

现在,将获得的 当前时间 值作为参数传递给 setTimedtamp() 方法,其中另一个参数将是占位符 ? 的参数索引整数,您需要在此处设置当前时间戳值。

pstmt.setTimestamp(2, new Timestamp(time));

更新于: 2019 年 7 月 30 日

6K+ 次查看

启动你的 职业生涯

通过完成课程获得认证

开始
广告

© . All rights reserved.