Java: creating a date object from a string and inserting into MySQL

本秂侑毒 提交于 2019-12-20 06:27:47

问题


Anytime I have to handle dates/times in java it makes me sad

I'm trying to parse a string and turn it into a date object to insert in a preparepared statement. I've been trying to get this working but am having no luck. I also get the helpful error message when I go to compile the class.

"Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method setDate(int, Date) in the type PreparedStatement is not applicable for the arguments (int, Date)"

Eh WTF?

Here is the offending code.

for(int i = 0; i < flights.size(); i++){

    String[] details = flight[i].toString().split(":"); 
    DateFormat formatter ; 
    formatter = new SimpleDateFormat("ddMMyyyy");
    Date date = formatter.parse(details[1]); 

    PreparedStatement pstmt = conn.prepareStatement(insertsql);
    pstmt.setString(1, details[0]);
    pstmt.setDate(2, date);
    pstmt.setString(3, details[2] + "00");
    pstmt.setString(4, details[3]);
    pstmt.setString(5, details[4]);
    pstmt.setString(6, details[5]);
    pstmt.setString(7, details[6]);
    pstmt.setString(8, details[7]);
    pstmt.setString(9, details[8]);
    pstmt.executeUpdate();

}

回答1:


PreparedStatement.setDate takes a java.sql.Date, not a java.util.Date.

(Out of interest, how come you're not actually seeing this as a compile-time error? Your life will become a lot easier if you can resolve compilation failures without having to get to that point in a test run...)




回答2:


My guess is that you mixed java.util.Date and java.sql.Date ...




回答3:


String to MySQL Date/Time

import java.sql.Date;
import java.sql.Time;

 statement.setDate(4, Date.valueOf("2009-08-26"));
 statement.setTime(5, Time.valueOf("12:04:08"));


来源:https://stackoverflow.com/questions/370852/java-creating-a-date-object-from-a-string-and-inserting-into-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!