如何使用MySQL自动增量列?

时间:2017-09-09 14:10:41

标签: java mysql sql jdbc sqlexception

我尝试在Java程序中使用MySQL auto_increment。但是我遇到了这种错误:

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

这是我的计划:

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 个答案:

答案 0 :(得分:1)

您忘记绑定第一个参数因此错误。您只需设置第二个参数的值

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

你应该有另一句话说:

pst.setString(1, "ValueYouWant");

或者

pst.setTimestamp(1, <function_that_returns_a_timestamp>);

取决于该列的预期值类型。

如果您不想自己添加当前时间戳,只需在表中将time列默认值设置为CURRENT_TIMESTAMP即可。