如何使用java prepare语句更新mysql timestamp列?

时间:2014-07-30 07:06:27

标签: java mysql sql jdbc prepared-statement

我创建了如下表格:

create table sample(id int not null,created_at timestamp,updated_at timestamp,name varchar(100),primary key(id));

尝试以不同的方式更新列,如下所示,但无法更新时间:

Calendar calender = Calendar.getInstance();
java.util.Date now = calender.getTime();
java.sql.Timestamp updatedAt = new java.sql.Timestamp(now.getTime());
stmt.setTimestamp(2, updatedAt);

java.sql.Timestamp  updatedAt = new java.sql.Timestamp(new java.util.Date().getTime());
stmt.setTimestamp(2, updatedAt);

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String updatedAt =sdf.format(date);
stmt.setString(2, updatedAt);

final java.util.Date updatedAt = new java.util.Date(System.currentTimeMillis());
stmt.setDate(2, new java.sql.Date(updatedAt.getTime()));

请帮我解决这个问题?

1 个答案:

答案 0 :(得分:1)

由于SQL约定,java.sql.Date()会删除日期的时间部分。您可以查看SQL-92 standard

Timestamp updatedAt = new Timestamp(Calendar.getInstance().getTimeInMillis());
stmt.setTimestamp(2, updatedAt);