如何使用Java在MySQL中插入当前时间 [英] How to insert current time in MySQL using Java

查看:408
本文介绍了如何使用Java在MySQL中插入当前时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将当前日期和时间(毫秒)插入MySQL。我做了以下事情:

I need to insert the current date and time (milliseconds) into MySQL. I did the following:

long time = System.currentTimeMillis();
java.sql.Timestamp timestamp = new java.sql.Timestamp(time);
System.out.println("Time in milliseconds :" + timestamp);

我得到的时间以毫秒为单位(例如2013-03-21 00:08:33.523) 。但是,我需要将此信息插入MySQL数据库。我尝试使用 PreparedStatement

And I got the time in milliseconds correctly (e.g. 2013-03-21 00:08:33.523). However, I need to insert this information into MySQL database. I tried the following using PreparedStatement

prepStmt.setTimestamp(2,timestamp);

但是插入的时间没有毫秒(例如2013-03-21 00:08:33)。

But the time is inserted without milliseconds (e.g. 2013-03-21 00:08:33).

如何以毫秒插入时间。

How can I insert the time with milliseconds.

编辑:数据库中的列是 DATETIME 类型。

The column in the database is of DATETIME type.

推荐答案

java.util.Date date = new java.util.Date();
java.sql.Timestamp timestamp = new java.sql.Timestamp(date.getTime());
preparedStatement.setTimestamp(1, timestamp);

这篇关于如何使用Java在MySQL中插入当前时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆