简体   繁体   中英

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:

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

Change the column names to the actual ones.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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