Search code examples
javasqloracle-databasejdatechooser

Insert date from JDateChooser into Oracle DB


I've been trying to use JDateChooser to insert a date into my Oracle db but I keep getting this error:

SQL Error: ORA-01861: literal does not match format string.

Here is my code.

        private void addActionPerformed(java.awt.event.ActionEvent evt) {                                    
    // TODO add your handling code here:
    try{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String d = sdf.format(tdate.getDate());
        System.out.println(d);

    String sql ="INSERT INTO TRACK(TRACKID,TRACKNAME,TRACKDESC,TRACKDATE)VALUES (?,?,?,?)";
        ps=conn.prepareStatement(sql);
        ps.setString(1,tid.getText());
        ps.setString(2,tname.getText());
        ps.setString(3,td.getText());
        ps.setString(4,d);
        ps.execute();

        JOptionPane.showMessageDialog(null, "Added");
    }
    catch(Exception e)
    {
        JOptionPane.showMessageDialog(null,e);
    }

}                            

Solution

  • Use setDate instead of setString for the fourth argument.

    ps.setDate(4, new java.sql.Date(tdate.getDate().getTime());
    

    More info about setting dates Using setDate in PreparedStatement