首页 > 解决方案 > 如果其中一列是使用准备好的语句自动递增,如何在 mysql 数据库中插入值

问题描述

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);
    }
}

我得到了这个例外:

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).

请帮我纠正代码。

标签: javamysqljdbcprepared-statementsqlexception

解决方案


?占位符不能用单引号括起来。
此外,最好在语句中包含将接收每个提供的值的列名。
如果第一列是自增列,那么你应该从列表中省略它,因为它的值将由 MySql 提供:

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

将列名称更改为实际名称。


推荐阅读