PreparedStatement SQL, :
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 this, you let the JDBC driver convert it to the format that the database expects so that your program remains independent of the database (you don't have to deal with formatting it the way MySQL expects it yourself).
When querying a database, also use PreparedStatementand use the getTimestamp()on method ResultSetto get the date as an object java.sql.Timestamp.
source
share