How to Insert Date and Time in MySQL Using Java

Step by step instructions to Insert Date and Time in MySQL Using Java

In this example, I will show you the most straightforward approach to embed date and time in MySQL database using Java.

This example is for embeddings current date and time. You can parse any date and time to embed. The following are the means to do this.

The most effective method to Insert Date and Time in MySQL Using Java

  1. First set up an association with MySQL database.
  2. Presently create an object of java.utl.Date of class.
  3. After that create objects of java.sql.Date and java.sql.Timestamp. Their constructor will take an object of java.util.Date class as a contention. The getTime() strategy is utilized to get the current date or time.
  4. The java.sql.Date class is utilized for date and java.sql.The timestamp is utilized for putting away time.
  5. Presently set up an announcement with embed question.
  6. The setDate() strategy is utilized to set date while setTimestamp() is utilized to set time.
  7. At last, execute the inquiry by executeUpdate() strategy to embed the date and time in the database.

Underneath I have shared an example for this.


package com;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class DateTimeExample {
	public static void main(String args[]){
			Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/demo","root","root");
			java.util.Date date=new java.util.Date();
			java.sql.Date sqlDate=new java.sql.Date(date.getTime());
			java.sql.Timestamp sqlTime=new java.sql.Timestamp(date.getTime());
			PreparedStatement ps=con.prepareStatement("insert into record (date,time) values(?,?)");
		}catch(Exception e){


How to Insert Date and Time in MySQL Using Java

In the wake of including the record, the table will resemble.

Remark underneath on the off chance that you have any questions identified with above instructional exercise.

Leave a Comment

error: Alert: Content is protected!!