Java: create date object from string and insert into MySQL

Anytime I have to handle dates / times in java I get sad

I am trying to parse a string and turn it into a date object to insert into a readypared statement. I tried to get this to work, but I had no luck. I also get a helpful error message when I go to compile the class.

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

Eh WTF?

Here is the violation 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();

}

      

0


source to share


3 answers


PreparedStatement.setDate takes java.sql.Date and not java.util.Date .



(Out of interest, why don't you actually see this as a compile-time error? Your life will be much easier if you can resolve compilation failures without being able to get to that point in a test run ..)

+8


source


I assume you have mixed java.util.Date and java.sql.Date ...



+4


source


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

      

+1


source







All Articles