Java JDBC: Insert Java 8 LocalDate and Time using PreparedStatement


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));
Insert Java 8 LocalDate and LocalDateTime using Java JDBC Example


Have Questions? Post them here!
Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.