DawgVonT DawgVonT - 1 month ago 14
Java Question

Java MySQL with prepared statement says parameter index out of range

I've looked on here before, but none of the answers helped me out!
I have the following code:

public void addSerialToDb(String serial) {
System.out.println(serial);
try{
System.out.println(getMaxInt());
}catch (Exception e){
e.printStackTrace();
}
String serialV2 = ""+serial;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, user, password);
pst = con.prepareStatement("INSERT INTO blogdata.serials" + "VALUES(?, ?)");
pst.setInt(1, getMaxInt());
pst.setString(2, serialV2);
pst.executeUpdate();
}catch (Exception e) {
e.printStackTrace();
}

closeDataBase();
}


In my database scheme, there are 2 collumns, first one is integer (id) and second one is a VARCHAR(45) (serial). But still I get the following error:

java.sql.SQLException: Parameter index out of range (2 > number of parameters, which is 0).
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:897)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:886)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
at com.mysql.jdbc.PreparedStatement.checkBounds(PreparedStatement.java:3321)
at com.mysql.jdbc.PreparedStatement.setInternal(PreparedStatement.java:3306)
at com.mysql.jdbc.PreparedStatement.setString(PreparedStatement.java:4021)
at DataBase.SerialDataBase.addSerialToDb(SerialDataBase.java:41)


I used this method on another program, but since switched to IntelliJ it stopped working.

Thanks in advance!

EDIT:
I forgot to mention, I'm using Java 1.8, the mySql connector 5.1.40 and running MySql 5.7.15

Answer

According to your comment getMaxInt() method, the problems is because of prepare statement object. It's being updated in getMaxInt() method and parameters not match error occurred. I think it's program logic error and you just need to change this program logic. I also recommend to not concat the String if it's not needed.

Below is just ok.

 pst = con.prepareStatement("INSERT INTO blogdata.serials (column1,column2) VALUES (?,?)";
Comments