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
package com; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; public class DateTimeExample { public static void main(String args[]){ try{ Class.forName("com.mysql.jdbc.Driver"); 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(?,?)"); ps.setDate(1,sqlDate); ps.setTimestamp(2,sqlTime); ps.executeUpdate(); ps.close(); con.close(); }catch(Exception e){ e.printStackTrace(); } } }
After adding the record the table will look like.
Comment below if you have any doubts related to above tutorial.
Thank you for this post. Good luck.
Thank you!
Thank neeraj bhai.
Thank You !!
Thank for all helps !!
What is the method for nextLine() in date datatype.
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.
I want to insert a date other than the current date. How would I do that? Thank you for your time.