我有以下代码,我想确保user_entered_student_id等于现有的user_id。如何通过SQL语句将所有user_id与user_entered_student_id进行比较?
System.out.println("\nSign Up For a Class\n");
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ClassSelector?autoReconnect=true&useSSL=false", "root", "Volks91!");
System.out.println("Enter Student ID: ");
user_entered_student_id = sc.nextLine();
String selectClassId = "SELECT class_id FROM ClassSelector.classes";
myStmt = con.prepareStatement(selectClassId);
rs = myStmt.executeQuery(selectClassId);
while (rs.next()) {
if (selectClassId.equals(user_entered_student_id)) {
System.out.println("This is not a valid User ID");
}
else {
String selectStudentFromIdQuery = ("SELECT student_name FROM ClassSelector.students WHERE student_id = " + user_entered_student_id);
myStmt = con.prepareStatement(selectStudentFromIdQuery);
rs = myStmt.executeQuery(selectStudentFromIdQuery);
while (rs.next()) {
userEnterIdAsName = rs.getString("student_name");
System.out.println("Is " + userEnterIdAsName + " the correct student? (Y/N)");
String confirm = sc.nextLine();
if (confirm.equalsIgnoreCase("Y")) {
addClass();
} else if (confirm.equalsIgnoreCase("N")) {
System.out.println("Oops, let start over");
return;
}
}
}
}
} catch ( java.sql.SQLException SQL ) {
SQL.printStackTrace();
}
}
答案 0 :(得分:0)
应用程序关闭的原因是,在您的else块中,查询不会为不存在的学生返回任何内容,因此while (rs.next())...
首先考虑运行检查作为结果集,如果数据为空,则next()
返回false。另请注意SQL参数化的使用(防止sql注入)。此外,结果集可以滚动以在检查后准备好为现有学生循环时返回到第一位:
String selectStudentFromIdQuery = ("SELECT student_name FROM ClassSelector.students " +
"WHERE student_id = ?");
myStmt = con.prepareStatement(selectStudentFromIdQuery,
ResultSet.TYPE_SCROLL_INSENSITIVE);
myStmt.setInt(1, user_entered_student_id);
rs = myStmt.executeQuery();
if (!rs.next()) {
System.out.println("Not an actual student");
}
rs.beforeFirst();
while (rs.next()){
userEnterIdAsName = rs.getString("student_name");
...
}