Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting date into MySQL database using a PreparedStatement

I want to update the string date into MySQL database using prepared statement. I have tried a lot and always got error java.util.Date cannot parse into java.sql.Date or vise versa. I didn't import anything here. Please import according to your answer.

public class Date1 
{ 
    public static void main(String args[]) 
    {
        String source="2008/4/5";              
        SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");                       
        java.sql.Date d=(Date) format.parse(source);             
        Class.forName("com.mysql.jdbc.Driver");        
        Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/employee", "root", "root");   
        PreparedStatement ps=con.prepareStatement("insert into ankur1 values(?)");          
        ps.setDate(1,(java.sql.Date) d);    
        ps.executUpdate();
    }
}
like image 441
ankur jadiya Avatar asked Dec 27 '22 16:12

ankur jadiya


1 Answers

Write this

java.sql.Date d= new java.sql.Date(format.parse(source).getTime());

instead of this:

java.sql.Date d=(Date) format.parse(source);

Because you cannot just cast java.util.Date to its subtype java.sql.Date. You have to convert it. Do also note that your format string doesn't match your actual date format, as Bill the Lizard commented.

like image 125
Lukas Eder Avatar answered Jan 13 '23 16:01

Lukas Eder