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.

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

  1. Some things you didn’t mention 1. If you want to store a timestamp, let’s say the creation of an object into a database which one to use? because storing ‘sqlTime’ actually doesn’t work. Once you retrieve that ‘sqlTime’ value stored in the database, it’s not the original time. it’s always the current time.

Leave a Comment

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