Share on Google+Share on Google+

Insert current date into MYSQL database

In this tutorial, you will learn how to insert current date into database.

Insert current date into MYSQL database

In this tutorial, you will learn how to insert current date into database.

In most of the applications, there is a need to insert date or time to database. Mysql provides several datatypes to store dates in the database system like DATE, TIMESTAMP, DATETIME and YEAR. This has made easy to save the data into database. The default way of storing the date in MySQL is by using DATE and the proper format of DATE is: YYYY-MM-DD. If you will enter a date in another format, it wouldn't store the date you want to save.


    import java.sql.*;

    class  InsertDate{
    	public static void main(String[] args){
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
                  		String sql = "insert into person(id, datefield) values(?, ?)";
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, 6);
			java.sql.Date sqlDate = new java.sql.Date(new java.util.Date().getTime());
			pstmt.setDate(2, sqlDate);
        catch(Exception e){

Description of Code: In this example, we have created a database connection and using the PreparedStatement, we have send the SQL statement to the database. Here, we are going to insert the id and date to a database table. The method setInt() set integer parameter of PreparedStatement. And to insert current date to database, we have created an instance of Date class of java.sql package and pass the current date to it using Java.util.Date class. The method setDate() set the date parameter to PreparedStatement. The method executeUpdate() saves the data to database.


Posted on: September 20, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.