Search code examples
javamysqljdbcprepared-statementsqlexception

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.


Solution

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