2011-12-20 36 views
2

我有以下結構:的Java JDBC訪問多個結果

列表 - > List_Participant - >參與者

所以列表可以有若干participants.I嘗試在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; 

我現在該如何ADRESS列,因爲它們可能具有相同的名字嗎?

+4

你沒有在數據庫進行連接的原因?看起來像是明顯的解決方案。 – 2011-12-20 17:45:31

+1

您應該儘可能地將作業委託給SQL語言,以便它僅在一個SQL查詢中完全返回**您想要的結果。這對Java和數據庫都是雙贏的。學習'JOIN'子句。 – BalusC 2011-12-20 18:05:23

+0

@JonSkeet:的確如此。我只是不習慣SQL。我怎麼會一次做兩個連接?這樣我就可以獲得所有列表中的所有參與者。我用現狀更新了答案。喬恩請寫你的評論作爲答案,所以我可以標記它! – Anthea 2011-12-20 18:40:30

回答

8

您可以嘗試使用兩個不同的Statement實例爲每個查詢。請參閱JavaDoc的java.sql.Statement。以下示例顯示了原理。

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罪你唯一的陳述。這可以由DB進行優化:

SELECT lp.* FROM list l JOIN List_Participant lp ON l.name = lp.name 

添加你喜歡檢索的數據最小化任何過濾器/條件。

+0

這是正確的答案。你應該用一些示例代碼和/或一兩個鏈接來擴展它。以下是一個很好的鏈接,例如:http://docs.oracle.com/javase/6/docs/api/java/sql/Statement.html – Gray 2011-12-20 18:45:11

+0

正如@Gray指出的那樣,Java 6 API語句允許它:'因此,如果一個ResultSet對象的讀取與另一個ResultSet對象的讀取交錯,則每個對象必須由不同的Statement對象生成 – ATorras 2016-02-29 17:42:57

0

嵌套查詢? 類似Select * from List_Participant where name in (select name from List); 這也可以用於您的第三個tabel。