Search code examples
javasql-serverdatetimestampsqlexception

java.util.Date to java.sql.Date doesn't contain Time


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

The uniqueness constraint is on the buzz_timestamp; that is, no 2 records may have the same date/time "timestamp".

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

So you can see I'm taking java.util.Date() ("now") and converting it to a java.sql.Date instance.

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.

So I ask: How do I correct this so that I'm truly inserting the date and time for "now"?


Solution

  • Use

    ps.setTimestamp(new java.sql.Timestamp(System.currentTimeMillis());
    

    See this: Using setDate in PreparedStatement