![](/img/trans.png)
[英]PostgreSQL & JDBC "Multiple ResultSets were returned by the query"
[英]java jdbc accessing multiple resultsets
我有以下結構:
列表 -->List_Participant -->參與者
所以一個列表可能包含幾個參與者。我嘗試在 java 中閱讀:
stat = con.createStatement();
ResultSet rs = stat.executeQuery("select * from list;");
// get the informations about the bracket sheet
while (rs.next()) {
string name = rs.getString("Name");
ResultSet rs2 = stat.executeQuery("select * from List_Participant where name= '"+name+"';");
while (rs2.next()) {
// get the participants
}
rs2.close();
}
rs.close();
但這不起作用。 我沒有收到異常或任何其他輸出。 我建議打開第二個結果集將關閉第一個結果集,因為因為我做了第一個結果集,所以將數據存儲在一個數組列表中並關閉它,然后第二個它會起作用,但這會導致性能不佳,因為我必須始終在數組列表。
什么可能是更好的解決方案?
編輯:解決方案是加入,我目前的嘗試:
select * from List_participant
INNER JOIN List ON List.name = List_participant.List
INNER JOIN participant ON List_participant.participant =participant.ROWID;
我現在如何處理這些列,因為它們可能具有相同的名稱?
您可以嘗試為每個查詢使用兩個不同的Statement
實例。 請參閱java.sql.Statement的 JavaDoc。 下面的例子展示了這個原理。
Statement statement1 = connection.createStatement();
Statement statement2 = connection.createStatement();
ResultSet resultSet1 = statement1.executeQuery("select * from list");
while (resultSet1.next()) {
String name = resultSet1.getString("Name");
ResultSet resultSet2 = statement2.executeQuery(
"select * from List_Participant where name= '" + name + "'");
while (resultSet2.next()) {
// get the participants
}
}
但是:這不是 JDBC 或 SQL 的標准用法,這是有充分理由的。 它剝奪了數據庫的任何優化可能性,並無緣無故地轉移到數據庫和您的應用程序之間的大量數據(參見 JohnSkeet 和 BalusC 的評論)。
最好在您的唯一聲明中使用適當的JOIN
。 這可以通過數據庫進行優化:
SELECT lp.* FROM list l JOIN List_Participant lp ON l.name = lp.name
添加您喜歡的任何過濾器/條件以最小化檢索到的數據。
這就是為什么你不能從同一個Statement
打開兩個ResultSet
的原因
當生成它的 Statement 對象關閉、重新執行或用於從多個結果序列中檢索下一個結果時,ResultSet 對象將自動關閉。
所以基本上,一個Statement
一次只能給你一個ResultSet
,所以當你執行第二個查詢時你會丟失第一個結果。
解決方案 :
ResultSet
需要使用一個Statement
實例。嵌套查詢? 類似於Select * from List_Participant where name in (select name from List);
這也適用於您的第三個表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.