1
那裏。 我是一個初學者使用java。我想爲我的SQL查詢結果做一個嵌套的while循環。JDBC嵌套while循環
我最初的結果就像下面,
eno ename title date_visit ssn pname charge
103 Jekyl Doctor 20170717 946883650 Gershwin 125
106 Ratchet Nurse 20170817 946883650 Gershwin 125
103 Jekyl Doctor 20170917 946883650 Gershwin 182
104 Caligari Doctor 20170707 831287780 Schubert 182
106 Ratchet Nurse 20170930 799023031 Haydn 190
102 Welby Doctor 20170818 416806352 Bernstein 210
102 Welby Doctor 20170808 874136439 Brahms 245
104 Caligari Doctor 20170808 796235486 Wagner 245
102 Welby Doctor 20170929 445139565 Chopin 405
102 Welby Doctor 20170910 874136439 Brahms 512
103 Jekyl Doctor 20170910 524246868 Verdi 512
103 Jekyl Doctor 20170909 129141378 Vivaldi 667
103 Jekyl Doctor 20170909 524246868 Verdi 667
,我寫我的Java語句像下面,
//Now we execute our query and store the results in the myresults object:
ResultSet myresults1 = stmt1.executeQuery("SELECT DISTINCT eno, ename, title FROM Staff_Activity");
ResultSet myresults2 = stmt2.executeQuery("SELECT eno, ename, title, date_visit, ssn, pname, SUM(charge) AS total_charge FROM Staff_Activity GROUP BY eno, ename, title, date_visit, ssn, pname");
System.out.println("Employee_ID\tEmployee_Name\tTitle");
System.out.println("-----------\t-------------\t------"); //Print a header
while (myresults1.next()) { //pass to the next row and loop until the last
System.out.println(myresults1.getInt("eno") + "\t\t" + myresults1.getString("ename") + "\t\t" + myresults1.getString("title"));
while (myresults2.next()) {
if (myresults1.getInt("eno")==(myresults2.getInt("eno"))) {
System.out.println(myresults2.getInt("date_visit") + "\t\t" + myresults2.getInt("ssn") + "\t\t" + myresults2.getString("pname") + "\t\t" + myresults2.getInt("total_charge"));
}//Print the current row
}
System.out.println();
}
我只得到了結果我的表中只有一名工作人員,
Employee_ID Employee_Name Title
----------- ------------- ------
103 Jekyl Doctor
20170909 524246868 Verdi 667
20170909 129141378 Vivaldi 667
20170910 524246868 Verdi 512
20170717 946883650 Gershwin 125
20170917 946883650 Gershwin 182
106 Ratchet Nurse
102 Welby Doctor
104 Caligari Doctor
真的想知道我的代碼有什麼問題。
在此先感謝。
謝謝你的評論。當我嘗試使用PreparedStatement時工作得很好。 –