這是我想出的。它定義了一個名爲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
那麼,什麼是問題? – Octahedron 2013-05-11 20:20:53
請參閱這裏以獲取建議:http://stackoverflow.com/q/192220/154439 – mwolfe02 2013-05-12 02:20:47