我正在开发一个场景,我必须在JDBC中执行SQL查询,以查找有关在特定主题中注册的学生的信息。运行此查询时,应一次显示3条记录。然后提示用户按Enter返回主菜单或按B继续浏览结果或输入StudentID以提取前一学期的结果。在下面的代码中,显示3个结果后,当用户按Enter或B时,我的代码可以正常工作。但是,在输入StudentID并运行子查询后,代码会自动显示主菜单。我希望它返回并继续显示剩余的结果,就像选项B一样浏览。
以下是代码段:
// Below is the SQL query that will be executed
// This snippet is part of loop where all different subjects are entered into an array and then user selects one subject
String displayStudent = "select * from students where subject = '" + subjectArray[choice - 1] + "'";
ResultSet displayThisList = stmt.executeQuery(displayStudent);
while (displayThisList.next()) {
System.out.println("Fname: " + displayThisList.getString(2));
System.out.println("Lname: " + displayThisList.getString(3));
System.out.println("StudentID: " + displayThisList.getString(1));
System.out.println("Grade: " + displayThisList.getString(4));
System.out.println("Subject: " + displayThisList.getString(5));
System.out.println();
subCount++;
if ((subCount % 3 == 0)) {
String response = readEntry("Enter StudentID to view last semester results or\nB Enter to browse or \nENTER to go back:");
System.out.println();
if (response.equals("")) {
// Back to member menu
break;
} else if (response.equals("B")) {
// Continue to browse
continue;
} else {
// Check if the StudentID is valid or not
int checkID = 0;
String queryID = "select * from students where StudentID='" + response + "'";
ResultSet setID = stmt.executeQuery(queryID);
while (setID.next()) {
String FName = setID.getString(2);
String LName = setID.getString(3);
String Grade = setID.getString(4);
String Subject = setID.getString(5);
checkID++;
System.out.println("Correct ID was entered");
//Code to execute query based on above info from a different table
}
if (checkID == 0) {
System.out.println();
System.out.println("Invalid ID. Please enter again.");
System.out.println();
}
}
}
}
答案 0 :(得分:2)
首先,对于不同的查询,您不应使用相同的Statement
对象如果您可以互换使用相应的ResultSet
。为“外部”查询创建一个语句,为子查询创建另一个语句。
其次,在while
- 循环(setId.next()
)中,您可能会从错误的ResultSet
(应setID.getString()
,而不是setISBN.getString()
)读取数据。
此外,如果基于用户输入生成SQL查询,您肯定应该使用PreparedStatement
。当有人输入StudentId
时,请考虑将会发生什么:
'; delete from students; select * from students where StudentID='foobar