How to Insert Date and Time in MySQL Using Java

In this example I will show you the simplest way to insert date and time in MySQL database using Java.

This example is for inserting current date and time. You can parse any date and time to insert. Below are the steps to do this.

 

How to Insert Date and Time in MySQL Using Java

1. First establish connection with MySQL database.

2. Now create an object of java.utl.Date class.

3. After that create objects of java.sql.Date and java.sql.Timestamp. There constructor will take object of java.util.Date class as an argument. The getTime() method is used to get current date or time.

4. The java.sql.Date class is used for date and java.sql.Timestamp is used for storing time.

5. Now prepare a statement with insert query.

6. The setDate() method is used to set date while setTimestamp() is used to set time.

7. Finally execute the query by executeUpdate() method to insert the date and time in database.

 

Below I have shared an example for this.

Example

 

After adding the record the table will look like.

How to Insert Date and Time in MySQL Using Java

Comment below if you have any doubts related to above tutorial.

2 thoughts on “How to Insert Date and Time in MySQL Using Java

Leave a Reply

Your email address will not be published. Required fields are marked *