0

I am having trouble trying to add dates to my database This is my code

 public void AddStudent(String idStudent, String name, String idClass, String dateOfBirth, String sex, String address){
        Connection connect = classConnection.connect;
        PreparedStatement ps = null;
        String query = "insert into students values(?,?,?,?,?,?)";
        try {
            ps = connect.prepareStatement(query);
            ps.setString(1, idStudent);
            ps.setString(2, name);
            ps.setString(3, sex);
            ps.setString(4, dateOfBirth);
            ps.setString(5, address);
            ps.setString(6, idClass);
            ps.execute();
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "Error: " + e.toString());
        } 
    }

This is an error

conversion failed when converting date and/or time from character string

I have to solve it like, thanks

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Nam Nguyen
  • 29
  • 1
  • You're submitting a value that cannot be parsed as a date or time. Show how you're calling this. – Jason May 16 '20 at 18:02
  • dateOfBirth is a String, but your 4th argument of the table students is not. – Gyro Gearloose May 16 '20 at 18:07
  • 1
    See [Using setDate in prepared statement](https://stackoverflow.com/questions/18614836/using-setdate-in-preparedstatement). – George Z. May 16 '20 at 18:07
  • Please read [Insert & fetch java.time.LocalDate objects to/from an SQL database such as H2](https://stackoverflow.com/questions/43039614/insert-fetch-java-time-localdate-objects-to-from-an-sql-database-such-as-h2). It shows a superior approach. – Ole V.V. May 16 '20 at 19:05
  • @GeorgeZ. Using `PreparedStatement.setDate()` is the obsolete way. [The answer by Basil Bourque](https://stackoverflow.com/a/38809770/5772882) is very good, though. Also see my link for the modern approach. – Ole V.V. May 16 '20 at 19:20

1 Answers1

0

You need to parse it fist to date, on the same format as your database format(). For shortcut, you can use setDate from PreparedStatement;

hope this helps

rizesky
  • 424
  • 6
  • 13