JDBC: Inserting Date values into MySQL

37,302

PreparedStatement provides the methods setDate(..), setTimestamp(..), and setTime(..) to replace placeholders (?) with date type fields. Use them

String lastCrawlDate = "2014-01-28";
Date utilDate = new SimpleDateFormat("yyyy-MM-dd").parse(lastCrawlDate);
// because PreparedStatement#setDate(..) expects a java.sql.Date argument
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime()); 

Connection con = ...;
PreparedStatement p = con.prepareStatement("insert into JsonData (last_crawl_date) values(?))");
p.setDate(1, sqlDate);
Share:
37,302
PeakGen
Author by

PeakGen

CTO

Updated on July 09, 2022

Comments

  • PeakGen
    PeakGen almost 2 years

    I would like to know how to set Date values to MySQL database, using Java JDBC. Following is my code.

     String lastCrawlDate = "2014-01-28"
     PreparedStatement p = con.prepareStatement("insert into JsonData (last_crawl_date) values(?))");
    
     p.setDate(1, Date.valueOf(lastCrawlDate));
    

    As you can see, the lastCrawlDate is a String and in the format of yyyy/mm/dd.

    Following is how my table looks like and how the Date field is defined.

    enter image description here

    How can I do this?