How to insert DATE into a MySQL column value using Java?

MySQLMySQLi DatabaseJava

For this, you can use PreparedStatement from Java. Let us first create a table wherein one of the columns is ArrivalDate with DATE type −

mysql> create table DemoTable(
   PassengerId int,
   PassengerName varchar(40),
   ArrivalDate date
Query OK, 0 rows affected (0.82 sec)

The JAVA code is as follows to insert date −

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class InsertDateFromJava {
   public static void main(String[] args) {
      Connection con = null;
      PreparedStatement ps = null;
      try {
         java.util.Date javaDate = new java.util.Date();
         java.sql.Date mySQLDate = new java.sql.Date(javaDate.getTime());
         con = DriverManager.getConnection("jdbc :mysql ://localhost :3306/web?useSSL=false", "root","123456");
         String query = "insert into DemoTable(PassengerId,PassengerName,ArrivalDate) values(?,?,?) ";
         ps = con.prepareStatement(query);
         ps.setInt(1, 101);
         ps.setString(2, "Adam");
         ps.setDate(3, mySQLDate);
         System.out.println("Record is inserted with current Date......");
      } catch (Exception e) {

This will produce the following output of Java −

Record is inserted with current Date......

Following is the screenshot of the output −

Let us check the records of the table again −

mysql> select * from DemoTable;

This will produce the following output −

| PassengerId | PassengerName | ArrivalDate |
|         101 | Adam          | 2019-09-07  |
1 row in set (0.00 sec)

The screenshot is as follows −

Updated on 14-Feb-2020 10:23:16