Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to insert DATE into a MySQL column value using Java?
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);
ps.executeUpdate();
System.out.println("Record is inserted with current Date......");
} catch (Exception e) {
e.printStackTrace();
}
}
}
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 −

Advertisements