如何使用准备语句设置当前日期和时间? [英] How to set current date and time using prepared statement?
问题描述
我在数据库中有一列,数据类型为 DATETIME
。我想使用PreparedStatement将此列值设置为当前日期和时间。如何做?
使用 PreparedStatement#setTimestamp()
,您传递
。 html#currentTimeMillis%28%29rel =noreferrer> 系统#currentTimeMillis()
。
< pre class =lang-java prettyprint-override>
preparedStatement.setTimestamp(index,new Timestamp(System.currentTimeMillis()));
// ...
如果数据库支持它,您也可以调用一个DB特定的函数,用于设置当前时间戳。例如,MySQL支持 now()
。例如
String sql =INSERT INTO user(email,creationdate)VALUES(?,now ));
如果数据库支持它,请将字段类型更改为自动设置插入/更新时间戳的字段类型,例如 TIMESTAMP
,而不是MySQL中的 DATETIME
。
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?
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.
这篇关于如何使用准备语句设置当前日期和时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!