简体   繁体   English

在MySQL中使用java.util.Date对象插入当前日期和时间

[英]Insert current date and time using java.util.Date object in MySQL

I have a field in MySQL created_on with datatype DATETIME. 我在MySQL created_on有一个数据类型为DATETIME的created_on For that field, I have to insert the current date and time. 对于该字段,我必须插入当前日期和时间。 I have taken java.util.Date object. 我已经采取了java.util.Date对象。

Date dateobj = new Date()
String query = "insert into users(created_on) values(?)";
ps = con.prepareStatement(query);
ps.setDate(1, new java.sql.Date(dateobj.getTime()));
insert_flag=ps.executeUpdate();

The query is executing fine but it is inserting only current date with 00:00:00. 查询执行得很好,但是只插入当前日期为00:00:00。 I want current date and time (example: 2015-10-28 03:23:50) 我想要当前的日期和时间(例如:2015-10-28 03:23:50)

To insert a date and a time, you need to use setTimestamp instead of setDate and the datatype of your database column must be DATETIME (or TIMESTAMP). 要插入日期和时间,您需要使用setTimestamp而不是setDate并且数据库列的数据类型必须为DATETIME(或TIMESTAMP)。

Quoting setDate Javadoc: 引用setDate Javadoc:

The driver converts this to an SQL DATE value when it sends it to the database. 驱动程序将其发送到数据库时,将其转换为SQL DATE值。

and quoting MySQL documentation : 并引用MySQL文档

The DATE type is used for values with a date part but no time part. DATE类型用于具有日期部分但没有时间部分的值。

Working code: 工作代码:

ps.setTimestamp(1, new java.sql.Timestamp(new Date().getTime()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM