Interacting with MySQL Datetimes and Timestamps in Java
When working with both datetimes and timestamps in a MySQL database from a Java application, it's essential to understand how these data types are represented and handled in both environments.
Java Representation
In Java, dates are typically represented using the java.util.Date class, which encapsulates both date and time information with millisecond precision.
MySQL Representation
In MySQL, there are three main date and time data types:
Interaction Between Java and MySQL
When retrieving a TIMESTAMP value from MySQL into Java, the result is stored in a java.sql.Timestamp object, which is a subclass of java.util.Date. When inserting a date into MySQL using a PreparedStatement, the setTimestamp() method should be used to set the parameter value as a Timestamp object.
Example Code
To demonstrate how to interact with MySQL datetimes and timestamps from Java, consider the following code:
import java.sql.*; public class DatetimeExample { public static void main(String[] args) throws SQLException { // Establish a connection to the MySQL database Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name", "username", "password"); // Get a timestamp object representing the current date and time Timestamp timestamp = new Timestamp(System.currentTimeMillis()); // Create a prepared statement to insert data into the database PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO events (event_date, event_time) VALUES (?, ?)"); // Set the timestamp value as the first parameter preparedStatement.setTimestamp(1, timestamp); // Set the second parameter as the time part of the timestamp preparedStatement.setTime(2, new Time(timestamp.getTime())); // Execute the insert statement preparedStatement.executeUpdate(); // Retrieve the inserted data using a result set ResultSet resultSet = preparedStatement.executeQuery("SELECT event_date, event_time FROM events WHERE event_id = (SELECT LAST_INSERT_ID())"); // Get the timestamp from the result set Timestamp retrievedTimestamp = resultSet.getTimestamp("event_date"); // Convert the timestamp to a Java date Date retrievedDate = new Date(retrievedTimestamp.getTime()); // Print the retrieved date and time System.out.println("Retrieved date: " + retrievedDate); System.out.println("Retrieved time: " + new Time(retrievedTimestamp.getTime())); } }
In this example, we demonstrate how to use Timestamp objects to insert both the date and time parts into a MySQL database and retrieve them as Date and Time objects in Java.
The above is the detailed content of How Do Java and MySQL Handle Datetimes and Timestamps?. For more information, please follow other related articles on the PHP Chinese website!