这取决于您在此处找不到学生时想要发生的事情,有两种方法可以做到。
抛出异常(如果学生不存在,这将是一个错误)
try {
checkStatus("studentA");
} catch(StudentNotFoundException e) {
System.out.println("Student wasnt found!");
}
public static void checkStatus(String ID_No) throws SQLException, StudentNotFoundException {
try{
ResultSet rs;
String validStatus = "SELECT * FROM validation";
st = connection.createStatement();
rs = st.executeQuery(validStatus);
while(rs.next()){
getStudValid = rs.getString("ID_No");
getValidStatus = rs.getString("Validation");
if (!getValidStatus.equals("Accepted") && getStudValid.equals(ID_No)){
System.out.println("Student " + getStudValid + " Please complete the required pre-requisite processes.");
return;
} else if (getValidStatus.equals("Accepted") && getStudValid.equals(ID_No)){
System.out.println("Student " + getStudValid + " You are Enrolled!");
return;
}
}
throw new StudentNotFoundException(); // create this exception eg: class StudentNotFoundException extends Exception
rs.close();
} catch(SQLException e){
System.out.println("Updated "+ ID_No);
}
}
或者你可以返回一个值
int exists = checkStatus("studentA");
if(exists == 0)
System.out.println("Student wasnt found");
public static int checkStatus(String ID_No) throws SQLException{
try{
ResultSet rs;
String validStatus = "SELECT * FROM validation";
st = connection.createStatement();
rs = st.executeQuery(validStatus);
while(rs.next()){
getStudValid = rs.getString("ID_No");
getValidStatus = rs.getString("Validation");
if (!getValidStatus.equals("Accepted") && getStudValid.equals(ID_No)){
System.out.println("Student " + getStudValid + " Please complete the required pre-requisite processes.");
return 1; // found
} else if (getValidStatus.equals("Accepted") && getStudValid.equals(ID_No)){
System.out.println("Student " + getStudValid + " You are Enrolled!");
return 1; // found
}
}
return 0; // no student found
rs.close();
} catch(SQLException e){
System.out.println("Updated "+ ID_No);
return -1; // error occured
}
}