You might have noticed the preparedStatement.setDate method of Java JDBC users the older Date object, if you are wondering how to insert the new Java 8+ Date and Time API date objects to the Database using JDBC then you should be using preparedStatement.setObject
Example 1: with LocalDate
Connection connection = DriverManager.getConnection(url,userName,password);
PreparedStatement preparedStatement = connection.prepareStatement(insertQuery);
preparedStatement.setString(1, null);
preparedStatement.setString(2, "Andrew");
preparedStatement.setObject(3, LocalDate.of(1999, 07, 21));
preparedStatement.setString(4, "Ohio");
int result = preparedStatement.executeUpdate();
mysql> select * from my_uat.students;
+------------+--------------+---------------------+-----------------+
| student_id | student_name | student_dob | student_address |
+------------+--------------+---------------------+-----------------+
| 1 | Mike | 2001-07-22 00:00:00 | New York City |
| 2 | Alex | 2002-08-13 00:00:00 | Chicago |
| 3 | Sam | 2022-01-25 00:00:00 | Ohio |
| 4 | Andy | 2001-10-10 00:00:00 | Japan |
| 5 | Andrew | 1999-07-21 00:00:00 | Ohio |
+------------+--------------+---------------------+-----------------+
Example 2: with LocalDateTime
preparedStatement.setObject(3, LocalDateTime.of(1998, 11, 18,10,20,10));

Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Connection connection = DriverManager.getConnection(url,userName,password);
PreparedStatement preparedStatement = connection.prepareStatement(insertQuery);
preparedStatement.setString(1, null);
preparedStatement.setString(2, "Andrew");
preparedStatement.setObject(3, LocalDate.of(1999, 07, 21));
preparedStatement.setString(4, "Ohio");
int result = preparedStatement.executeUpdate();mysql> select * from my_uat.students;
+------------+--------------+---------------------+-----------------+
| student_id | student_name | student_dob | student_address |
+------------+--------------+---------------------+-----------------+
| 1 | Mike | 2001-07-22 00:00:00 | New York City |
| 2 | Alex | 2002-08-13 00:00:00 | Chicago |
| 3 | Sam | 2022-01-25 00:00:00 | Ohio |
| 4 | Andy | 2001-10-10 00:00:00 | Japan |
| 5 | Andrew | 1999-07-21 00:00:00 | Ohio |
+------------+--------------+---------------------+-----------------+preparedStatement.setObject(3, LocalDateTime.of(1998, 11, 18,10,20,10));

Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!