0

我正在处理一个场景,我必须在 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();
            }
        }
    }
}
4

1 回答 1

2

首先,如果可互换使用相应的对象,则不应将相同的Statement对象用于不同的查询。为“外部”查询创建一个语句,为子查询创建另一个语句。ResultSet

其次,在while-loop ( ) 中,您可能从错误(应该,不)中setId.next()读取数据。ResultSetsetID.getString()setISBN.getString()

此外,如果 SQL 查询是根据用户输入生成的,那么您绝对应该使用它PreparedStatement。考虑当有人进入时会发生什么StudentId

'; delete from students; select * from students where StudentID='foobar
于 2013-03-14T11:16:20.897 回答