JDBC UPDATE With preparedStatement causing java.sql.SQLException: Parameter index out of range (3 > number of parameters, which is 2) [duplicate]

浪子不回头ぞ 提交于 2019-12-20 03:51:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!