简体   繁体   English

如果列之一是使用准备好的语句自动递增,如何在 mysql 数据库中插入值

[英]How to insert values in mysql database if one of the column is auto increment using prepared statement

public String put(){
         this.query = "INSERT INTO user_registration VALUES('default', '?' , '?' , '?' , '?' , '?' );";

    try {
        PreparedStatement stmt= Main.connection.prepareStatement(query);
        stmt.setString(1,this.fullname);
        stmt.setString(2,this.username);
        stmt.setString(3,this.password);
        stmt.setString(4,this.email);
        stmt.setString(5,this.contact);
        stmt.executeUpdate();
        return String.valueOf(SignupStatus.SUCCESS);
    } catch (SQLException e) {
        e.printStackTrace();
        System.out.println(e);
        return String.valueOf(SignupStatus.FAILED);
    }
}

I am getting this exception:我收到此异常:

java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63)
    at com.mysql.cj.jdbc.ClientPreparedStatement.checkBounds(ClientPreparedStatement.java:1372)
    at com.mysql.cj.jdbc.ClientPreparedStatement.getCoreParameterIndex(ClientPreparedStatement.java:1385)
    at com.mysql.cj.jdbc.ClientPreparedStatement.setString(ClientPreparedStatement.java:1752)
    at client_sharenow.Signup.put(Signup.java:29)
    at client_sharenow.Client_Request.run(Client_Request.java:40)
    at java.base/java.lang.Thread.run(Thread.java:832)
java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).

Please help me out correcting the code.请帮我更正代码。

The ? ? placeholders must not be enclosed inside single quotes.占位符不能用单引号括起来。
Also it's good practice to include in your statement the column names that will receive each of the supplied values.此外,在您的语句中包含将接收每个提供的值的列名称也是一种很好的做法。
If the 1st column is the auto increment column then you should omit it from the list, because its value will be supplied by MySql:如果第一列是自动递增列,那么您应该从列表中省略它,因为它的值将由 MySql 提供:

this.query = "INSERT INTO user_registration(fullname, username, password, email, contact) VALUES (?, ?, ?, ?, ?);";

Change the column names to the actual ones.将列名称更改为实际名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM