开发者

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 for开发者_开发百科ward.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜