java.sql.SQLException: Parameter index out of range (2 > number of parameters, which is 1)
I have checked all the answers already in this topic but couldn't find the solution for my problem. No matter what changes I do it shows the exception. My code segment:
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!!");
}
}
**The code for checkDuplicateId method is below: **
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{
}
Your query only has one parameter, the last ?
.
UPDATE student SET name = '?', address = '?', email_address = '?', phone_no = '?' WHERE id = ?;
You are using a literal string '?'. Remove the quotation marks.
UPDATE student SET name = ?, address = ?, email_address = ?, phone_no = ? WHERE id = ?;
Right now you are just setting name
, address
, email_address
and phone_no
to "?".