java.util.Date到java.sql.Date不包含Time [英] java.util.Date to java.sql.Date doesn't contain Time
问题描述
我在 PreparedStatement
上收到 SqlException
,以违反表上的唯一约束(dupe key) 。基本上我的表格如下所示:
I'm getting a SqlException
on a PreparedStatement
for violating a uniqueness constraint on a table (dupe key). Essentially my table looks like this:
mytable
=======
mytable_id PRIMARY KEY INT NOT NULL
fizz_id INT NOT NULL
buzz_timestamp DATETIME
唯一性约束是在 buzz_timestamp
上;也就是说,没有2条记录可能具有相同的日期/时间timestamp。
The uniqueness constraint is on the buzz_timestamp
; that is, no 2 records may have the same date/time "timestamp".
插入记录的 PreparedStatement
进入这个表格如下所示:
The PreparedStatement
that inserts records into this table looks like this:
PreparedStatement ps = conn.prepareStatement(insertQuery);
ps.setDate(1, new java.sql.Date(new java.util.Date().getTime()));
所以你可以看到我正在采取 java.util.Date()
(now),并将其转换为 java.sql.Date
实例。
So you can see I'm taking java.util.Date()
("now") and converting it to a java.sql.Date
instance.
我正在看到的确切的错误(dupe键)不断抱怨说我试图将 2015-05-27 00:00:00.0000000
插入表格中 buzz_timestamp
,但它已经存在。所以很明显,我使用Date API错误,我插入的日期是空的时间组件,从而产生重复例外。
The exact error I'm seeing (the dupe key) keeps complaining that I'm trying to insert 2015-05-27 00:00:00.0000000
into the table for buzz_timestamp
, but that it already exists. So, obviously, I'm using the Date API wrong, and I'm inserting dates that have nulled-out time components, and thereby producing dupe key exceptions.
所以我问:我如何更正这个问题,以便真正插入现在的日期和时间?
推荐答案
使用
ps.setTimestamp(new java.sql.Timestamp(System.currentTimeMillis());
参见:在PreparedStatement中使用setDate
这篇关于java.util.Date到java.sql.Date不包含Time的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!