Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

mysql

jdbc

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.

like image 579
stdcall Avatar asked Dec 06 '22 19:12

stdcall


1 Answers

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");
// ...
like image 57
BalusC Avatar answered Dec 10 '22 11:12

BalusC