Handling MySQL Datetimes and Timestamps in Java
When working with MySQL databases in Java, it is often necessary to handle dates and times. MySQL supports both DATE and DATETIME types, which are represented in Java as java.sql.Date and java.sql.Timestamp respectively.
Storing Timestamps
To store a timestamp in the database, use the PreparedStatement#setTimestamp() method:
Timestamp timestamp = new Timestamp(date.getTime()); preparedStatement = connection.prepareStatement("SELECT * FROM tbl WHERE ts > ?"); preparedStatement.setTimestamp(1, timestamp);
Retrieving Timestamps
To retrieve a timestamp from the database, use the ResultSet#getTimestamp() method:
Timestamp timestamp = resultSet.getTimestamp("ts"); java.util.Date date = timestamp; // Upcast to java.util.Date
Handling Datetime:
MySQL also supports the DATE datatype, which represents only the date component. To work with this datatype, use the java.sql.Date class:
java.sql.Date date = resultSet.getDate("my_date");
Conclusion
By understanding the different date and time types supported by MySQL and Java, you can effectively handle this data in your applications.
The above is the detailed content of How Do I Handle MySQL DATE and DATETIME Types in Java?. For more information, please follow other related articles on the PHP Chinese website!