how to store java date type to mysql date type?
Use some instance of the Calendar class to convert the date to a string and use the string in your SQL query.
See that your Date
is a java.sql.Timestamp
(especially if you want hours,mins,sec.. to be persisted)
You could convert a java.util.Date
to a Timestamp
like so: new Timestamp(date.getTime())
Use a PreparedStatement
to execute the SQL statement, like this:
Date date = ...;
PreparedStatement ps = connection.prepareStatement("INSERT INTO mytable (this, that, datecol) values (?, ?, ?)");
ps.setString(1, "hello");
ps.setString(2, "world");
ps.setTimestamp(3, new java.sql.Timestamp(date.getTime()));
ps.executeUpdate();
When you do it like this, you let the JDBC driver convert it to the format that the database expects, so that your program can remain database independent (you don't need to deal with formatting it in the way that MySQL expects it yourself).
When querying the database, also use PreparedStatement
and use the getTimestamp()
method on the ResultSet
to get the date as a java.sql.Timestamp
object.