问题
I am facing java.sql.SQLException: Parameter index out of range (3 > number of parameters, which is 2). while updating one or two columns of 'reset_info' table which has five columns (id, mobile_tower_id, reset_value, date_time, clientip). 'id' is auto-generated primary key. I want to UPDATE 'reset_value' of a particular row
Now Following is the source code:
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
String sql = "UPDATE reset_info SET reset_value = ? WHERE id = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, 100);
ps.setInt(3, 1000);
ps.executeUpdate();
conn.close();
And Following is my stacktrace:
Connecting to database...
java.sql.SQLException: Parameter index out of range (3 > number of parameters, which is 2).
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1078)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:975)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:920)
at com.mysql.jdbc.PreparedStatement.checkBounds(PreparedStatement.java:3813)
at com.mysql.jdbc.PreparedStatement.setInternal(PreparedStatement.java:3795)
at com.mysql.jdbc.PreparedStatement.setInternal(PreparedStatement.java:3840)
at com.mysql.jdbc.PreparedStatement.setInt(PreparedStatement.java:3784)
at cdot.dsa.cfms.dbconnect.NewClass.main(NewClass.java:38)
Is it mandatory for to put placeholder('?') for each column of the table?
Updating a single column by java.sql.Statement is working but I am getting exception with java.sql.preparedStatement.
Please help. Conceptual ideas will be highly appreciated.
回答1:
This ps.setInt(3, 1000);
must be ps.setInt(2, 1000);
because you only have to placeholder.
Is it mandatory for to put placeholder('?') for each column of the table?
The placeholder is for a parameter not for a column!
回答2:
you have not more than two question marks(placeholder) in your statement. As a result of this, this must fail:
ps.setInt(3, 1000);
change it to
ps.setInt(2, 1000);
来源:https://stackoverflow.com/questions/29096480/jdbc-update-with-preparedstatement-causing-java-sql-sqlexception-parameter-inde