简体   繁体   中英

JDBC and MySQL, how to persist java.util.Date to a DATETIME column?

I'm struggling to understand how to get it to work. I have a prepared statment, and I want to persist a java.util.date. It doesn't work. I tried to cast it to java.sql.Date, and it still doesn't work. what's the issue with java date framework, it's really not straight forward.

You should use java.sql.Timestamp to store a java.util.Date in a DATETIME field. If you check the javadocs of both classes (click the above links!), you'll see that the Timestamp has a constructor taking the time in millis and that Date has a getter returning the time in millis.

Do the math:

preparedStatement.setTimestamp(index, new Timestamp(date.getTime()));
// ...

You should not use java.sql.Date as it represents only the date portion, not the time portion. With this, you would end up with 00:00:00 as time in the DATETIME field.

For your information only, since Timestamp is a subclass of java.util.Date , you could just upcast it whenever you obtain it from the ResultSet .

Date date = resultSet.getTimestamp("columnname");
// ...

This will do it:

int dateColumnId = 0; // or whatever the value needs to be.
java.util.Date incomingValue = new java.util.Date(System.currentTimeMillis());
java.sql.Date databaseValue = new java.sql.Date(incomingValue.getTime());   
ps.setDate(dateColumnId, databaseValue);

Maybe you can try this:

java.util.Date now = new java.util.Date();
java.sql.Date date = new java.sql.Date(now.getTime());
pstmt.setDate(columnIndex,date);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM