DawgVonT DawgVonT - 1 year ago 183
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) {
}catch (Exception e){
String serialV2 = ""+serial;
con = DriverManager.getConnection(url, user, password);
pst = con.prepareStatement("INSERT INTO blogdata.serials" + "VALUES(?, ?)");
pst.setInt(1, getMaxInt());
pst.setString(2, serialV2);
}catch (Exception e) {


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!

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

Answer Source

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 (?,?)";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download