为什么此代码显示参数索引超出范围异常?

Why this code shows parameter index out of range exception?

java.sql.SQLException: Parameter index out of range (2 > number of parameters, which is 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{


    }

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

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

您正在使用 字符串 '?'。删除引号。

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

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