How to work with MySQL auto increment columns?

173 Views Asked by At

I am try to use MySQL auto_increment in a Java program. But I'm getting this type of error:

Sep 09, 2017 7:36:16 PM demosub jButton1ActionPerformed SEVERE: null
java.sql.SQLException: No value specified for parameter 1

This is my program:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    try {
        String url = "jdbc:mysql://localhost:3306/anadha";
        String uname1 = "root";
        String password = "csrajesh";
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection(url, uname1, password);
        PreparedStatement pst = con.prepareStatement("INSERT into employee (time, name) VALUES (?,?)", Statement.RETURN_GENERATED_KEYS);
        pst.setString(2, nme.getText());
        pst.executeUpdate();
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(demosub.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(demosub.class.getName()).log(Level.SEVERE, null, ex);
    }
1

There are 1 best solutions below

1
On BEST ANSWER

You forgot to bind the first parameter therefore the error. You only set the value for the 2nd parameter

pst.setString(2, nme.getText());

You should have another line saying sth like :

pst.setString(1, "ValueYouWant");

Or

pst.setTimestamp(1, <function_that_returns_a_timestamp>);

Depending on what type of value is expected for that column.

If you do not want to add the current timestamp yourself just set the time column default value to be CURRENT_TIMESTAMP in the table.