为啥此代码显示参数索引超出范围异常? [复制]

Posted

技术标签:

【中文标题】为啥此代码显示参数索引超出范围异常? [复制]【英文标题】:Why this code shows parameter index out of range exception? [duplicate]为什么此代码显示参数索引超出范围异常? [复制] 【发布时间】:2017-07-19 07:32:17 【问题描述】:

java.sql.SQLException: 参数索引超出范围(2>参数个数,即1)

我已经检查了该主题中的所有答案,但找不到我的问题的解决方案。无论我做什么更改,它都会显示异常。 我的代码段:

public void updatetData() 
    System.out.println("Enter the id of the record you want to update :");
    int updateID = sc.nextInt();


    if(checkDuplicateId(updateID))
        sql = "UPDATE student SET name = '?', address = '?', email_address = '?', phone_no = '?' WHERE id = ?" ;
        try(Connection con = dbConn.getConnection();
                PreparedStatement stmtUpdate = con.prepareStatement(sql);) 


            System.out.println("\nEnter the name to update : ");
            String name = sc.next();
            System.out.println("\nEnter the address to update : ");
            String address = sc.next();
            System.out.println("\nEnter the email address to update : ");
            String email_address = sc.next();
            System.out.println("\nEnter the phone no to update : ");
            String phone_no = sc.next();


            stmtUpdate.setString(1, name);
            stmtUpdate.setString(2, address);
            stmtUpdate.setString(3, email_address);
            stmtUpdate.setString(4, phone_no);
            stmtUpdate.setInt(5, updateID);

            stmtUpdate.execute();
            System.out.println("Updation completed");


         catch (SQLException ex) 
            System.out.println("Exception in updateData");
            ex.printStackTrace();
        
     else
        System.out.println("ID doesn't exist!!");
    

**checkDuplicateId方法的代码如下:**

private boolean checkDuplicateId(int id)
    boolean checkDup = false;
    String sql1 = "SELECT * FROM student WHERE id = ?";
    try(Connection con = dbConn.getConnection();
            PreparedStatement stmt = con.prepareStatement(sql1);) 

        stmt.setInt(1, id);

        try(ResultSet rs = stmt.executeQuery();)
            if(rs.next())
                return !checkDup;
            else 
                return checkDup;
        
     catch (SQLException ex) 
        System.out.println("Exception occured  in checkduplicate method");
        ex.printStackTrace();
        return false;

     finally


    

【问题讨论】:

删除 ? 占位符周围的单引号。 【参考方案1】:

您的查询只有一个参数,即最后一个?

UPDATE student SET name = '?', address = '?', email_address = '?', phone_no = '?' WHERE id = ?;

您使用的是文字 string '?'。去掉引号。

UPDATE student SET name = ?, address = ?, email_address = ?, phone_no = ? WHERE id = ?;

现在您只是将nameaddressemail_addressphone_no 设置为“?”。

【讨论】:

谢谢它的工作:)

以上是关于为啥此代码显示参数索引超出范围异常? [复制]的主要内容,如果未能解决你的问题,请参考以下文章

指数超出范围。必须是非负数且小于集合的大小。参数名称:索引

创建任务时列出索引超出范围异常

错误:索引 1 超出范围 [0 .. 0]

Java JDBC SQLException:参数索引超出范围[重复]

为啥我没有得到数组超出范围错误? [复制]

PreparedStatement 参数索引超出范围