I have a column in database having datatype DATETIME
. I want to set this column value to current date and time using `PreparedStatement. How do I do that?
2 Answers
Use PreparedStatement#setTimestamp()
wherein you pass a java.sql.Timestamp
which is constructed with System#currentTimeMillis()
.
preparedStatement.setTimestamp(index, new Timestamp(System.currentTimeMillis()));
// ...
Alternativaly, if the DB supports it, you could also call a DB specific function to set it with the current timestamp. For example MySQL supports now()
for this. E.g.
String sql = "INSERT INTO user (email, creationdate) VALUES (?, now())";
Or if the DB supports it, change the field type to one which automatically sets the insert/update timestamp, such as TIMESTAMP
instead of DATETIME
in MySQL.
-
Hello Sir! As I mention the columns datatype in database is datetime so as in your solution you mention timestamp so please tell me is this solution will set current data and time to my datetime column? Oct 2, 2011 at 11:38
-
Yes, I know that. What exactly is the problem you're having with it? The
java.sql.Timestamp
just represents the Java type of the MySQLDATETIME
andTIMESTAMP
field types.– BalusCOct 2, 2011 at 11:40 -
-
-
1"The java.sql.Timestamp just represents the Java type of the MySQL DATETIME and TIMESTAMP field types" How could one object represent both types when they aren't the same? If you use
setTimestamp
andgetTimestamp
, does it muddle the data at all? Or are those methods sufficient to transfer the data whether your DB reflects aDATETIME
or aTIMESTAMP
? May 10, 2014 at 17:15
conn = getConnection();
String query = "insert into your_table(id, date_column) values(?, ?)";
pstmt = conn.prepareStatement(query);
pstmt.setString(1, "0001");
java.sql.Date date = getCurrentDatetime();
pstmt.setDate(2, date);
Where the function getCurrentDatetime() does the following:
public java.sql.Date getCurrentDatetime() {
java.util.Date today = new java.util.Date();
return new java.sql.Date(today.getTime());
}
-
10This only sets the date portion, not the time. OP uses a
DATETIME
field.– BalusCOct 2, 2011 at 11:40 -