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は、異なるクエリに同じオブジェクトを使用しないでください。「外部」クエリ用に1つのステートメントを作成し、サブクエリ用に別のステートメントを作成します。ResultSet

次に、while-loop(setId.next())で、おそらく間違ったデータを読み取りますResultSet(すべきsetID.getString()ではなく、そうではありませんsetISBN.getString())。

さらに、SQLクエリがユーザー入力に基づいて生成される場合は、PreparedStatement代わりに使用する必要があります。誰かが次のように入力したときに何が起こるかを考えてくださいStudentId

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