I have a field in MySQL created_on
with datatype DATETIME. For that field, I have to insert the current date and time. I have taken java.util.Date
object.
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. I want current date and time (example: 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).
Quoting setDate
Javadoc:
The driver converts this to an SQL DATE value when it sends it to the database.
and quoting MySQL documentation :
The DATE type is used for values with a date part but no time part.
Working code:
ps.setTimestamp(1, new java.sql.Timestamp(new Date().getTime()));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.