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 = 아프리카
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
깊이 중첩된 객체를 정확히 일치 검색 - PostgreSQL목차 * 🚀 * 🎯 * 🏁 * 🙏 JSON 객체 예시 따라서 우리의 현재 목표는 "고용주"사용자가 입력한 검색어(이 경우에는 '요리')를 얻고 이 용어와 정확히 일치하는 모든 사용자 프로필을 찾는 것입니다. 즐거운 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.