JDBC: Inserting Date values into MySQL

前端 未结 3 478
囚心锁ツ
囚心锁ツ 2021-01-12 08:42

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\"
 PreparedStateme         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-12 09:00

    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);
    

提交回复
热议问题