如何使用准备好的语句设置当前日期和时间? [英] How to set current date and time using prepared statement?
问题描述
我在数据库中有一个数据类型为 DATETIME
的列.我想使用PreparedStatement"将此列值设置为当前日期和时间.我该怎么做?
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?
推荐答案
使用 PreparedStatement#setTimestamp()
其中你传递了一个 java.sql.Timestamp
使用 System#currentTimeMillis()
.
preparedStatement.setTimestamp(index, new Timestamp(System.currentTimeMillis()));
// ...
或者,如果数据库支持它,您还可以调用特定于数据库的函数以使用当前时间戳设置它.例如 MySQL 支持 now()
为此.例如
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())";
或者如果 DB 支持,将字段类型更改为自动设置插入/更新时间戳的字段类型,例如 TIMESTAMP
而不是 MySQL 中的 DATETIME
.
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屋!