2013-05-11 48 views
1

我需要從Access數據庫讀入成員列表。每個成員都由另一個成員贊助。每條記錄都包含其贊助商的ID和他們自己的ID。我現在必須能夠高效地閱讀會員名冊並將其打印出來以顯示誰由誰贊助。構建樹和遍歷樹:> 2個兒子

我覺得最有效的方法是構建一棵樹,然後進行一次遍歷。

我的輸出應該是這個樣子:

Mary Jones 
    Kim Smith 
    Rena Brown 
     Joan Brown 
     Patsy Brown 
    Howard Sharp 
    Ken Johnson 
Peter Pan 
    Wendy 
    Hook 
Davey Crocket 
    … 

訂單將被按ID號。我找到的所有東西都是一個只有左右兒子的二叉樹。如你所見,這對我不起作用。

首選的解決方案是Java,但會感激我能得到的任何東西。

邦妮

+1

那麼,什麼是問題? – Octahedron 2013-05-11 20:20:53

+0

請參閱這裏以獲取建議:http://stackoverflow.com/q/192220/154439 – mwolfe02 2013-05-12 02:20:47

回答

0

這是我想出的。它定義了一個名爲ListSponsoredMembers功能,並調用它遞歸地建立列表:

import java.sql.*; 

public class ListSponsorship { 
    static Connection conn; 

    public static void main(String[] args) { 
     try { 
      conn = DriverManager.getConnection(
        "jdbc:ucanaccess://C:/Users/Public/Database1.accdb;"); 
      PreparedStatement ps1 = conn.prepareStatement(
        "SELECT memberID, memberName FROM Members " + 
        "WHERE sponsorID IS NULL ORDER BY memberID"); 
      ResultSet rs = ps1.executeQuery(); 
      while (rs.next()) { 
       ListSponsoredMembers(rs.getInt("memberID"), rs.getString("memberName"), 0); 
      } 
      ps1.close(); 
      conn.close(); 
     } catch(Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    private static void ListSponsoredMembers(Integer memberID, String memberName, Integer recursionLevel) { 
     for (Integer i = 0; i < recursionLevel; i++) { 
      System.out.print(" "); 
     } 
     System.out.println(memberName); 
     try { 
      PreparedStatement ps2 = conn.prepareStatement(
        "SELECT memberID, memberName FROM Members " + 
        "WHERE sponsorID=? ORDER BY memberID"); 
      ps2.setInt(1, memberID); 
      ResultSet rs = ps2.executeQuery(); 
      Integer newRecursionLevel = ++recursionLevel; 
      while (rs.next()) { 
       ListSponsoredMembers(rs.getInt("memberID"), rs.getString("memberName"), newRecursionLevel); 
      } 
     } catch (SQLException e) { 
      e.printStackTrace(); 
     } 
    } 

} 

對於[會員]表看起來像這樣...

memberID memberName  sponsorID 
-------- ------------- --------- 
     1 Mary Jones    
     2 Kim Smith    1 
     3 Rena Brown    1 
     4 Joan Brown    3 
     5 Patsy Brown   4 
     6 Howard Sharp   1 
     7 Ken Johnson   1 
     8 Peter Pan    
     9 Wendy     8 
     10 Hook     8 
     11 Davey Crocket   

...它產生以下輸出:

Mary Jones 
    Kim Smith 
    Rena Brown 
    Joan Brown 
     Patsy Brown 
    Howard Sharp 
    Ken Johnson 
Peter Pan 
    Wendy 
    Hook 
Davey Crocket 
+0

戈登,你的劇本很高雅,像魅力一樣工作。非常感謝。 – user2373577 2013-05-14 23:22:40