id, pid, 데이터베이스 재 귀적 호출 트 리 메뉴 의 예제

2663 단어 sql
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")+"
"; 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 = 아프리카

좋은 웹페이지 즐겨찾기