开发者

How to set current date and time using prepared statement?

I have a column in database having datatype DATETIME. I want to set this column va开发者_运维百科lue to current date and time using `PreparedStatement. How do I do that?


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.


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());
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜