Home > Database > Mysql Tutorial > How Do I Handle MySQL DATE and DATETIME Types in Java?

How Do I Handle MySQL DATE and DATETIME Types in Java?

DDD
Release: 2024-12-14 20:00:19
Original
762 people have browsed it

How Do I Handle MySQL DATE and DATETIME Types in Java?

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);
Copy after login

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
Copy after login

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");
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template