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{
}
答案 0 :(得分:2)
您的查询只有一个参数,即最后一个?
。
UPDATE student SET name = '?', address = '?', email_address = '?', phone_no = '?' WHERE id = ?;
您使用的是文字字符串'?'。删除引号。
UPDATE student SET name = ?, address = ?, email_address = ?, phone_no = ? WHERE id = ?;
目前您只需将name
,address
,email_address
和phone_no
设置为"?"。