public class TreeDAO{ public String readTree(int id,int level){ String str = ""; Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = "SELECT * FROM earth WHERE pid=?"; try{ conn = DBConnect.getConn(); pstmt = conn.prepareStatement(sql); pstmt.setInt(1, id); rs = pstmt.executeQuery(); while(rs.next()){ for (int i = 0; i < level; i++) { str += "-->>"; } str += rs.getInt("id")+"="+rs.getString("name")+"\n"; str += readTree(rs.getInt("id"),++level); --level; } }catch(Exception e){ e.printStackTrace(); }finally{ DBConnect.closeRs(rs); DBConnect.closePstmt(pstmt); DBConnect.closeConn(conn); } return str; } public static void main(String[] args) { TreeDao treeDao = new TreeDao(); String str = treeDao.readTree(0, 1); System.out.println(str); } }
CREATE TABLE `earth` ( `id` int(11) NOT NULL, `pid` int(11) NOT NULL, `name` varchar(50) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; # # Dumping data for table earth # INSERT INTO `earth` VALUES (1,0,'亚洲'); INSERT INTO `earth` VALUES (2,0,'欧洲'); INSERT INTO `earth` VALUES (3,0,'美洲'); INSERT INTO `earth` VALUES (4,0,'非洲'); INSERT INTO `earth` VALUES (5,1,'中国'); INSERT INTO `earth` VALUES (6,1,'小日本'); INSERT INTO `earth` VALUES (7,1,'棒子'); INSERT INTO `earth` VALUES (8,3,'美国'); INSERT INTO `earth` VALUES (9,5,'北京'); INSERT INTO `earth` VALUES (10,5,'上海'); INSERT INTO `earth` VALUES (11,5,'西安'); INSERT INTO `earth` VALUES (12,9,'北京大学'); INSERT INTO `earth` VALUES (13,11,'西安交大');
out:
-->>1=亚洲
-->>-->>5=中国
-->>-->>-->>9=北京
-->>-->>-->>-->>12=北京大学
-->>-->>-->>10=上海
-->>-->>-->>11=西安
-->>-->>-->>-->>13=西安交大
-->>-->>6=小日本
-->>-->>7=棒子
-->>2=欧洲
-->>3=美洲
-->>-->>8=美国
-->>4=非洲