前言:大家在bbs回帖时常常可以看到树形的回复形式。
(1) 为使得Connection仅打开一次,因此以conn作为其中一个递归参数,在递归全程不关闭conn;
(2)根据存入数据的树状结构,由root的id逐层往下走;每到一个结点递归扫描该结点的子结点;
(3)打印时进行字符串拼接,故引入第三个递归参数:“level”;
create database bbs;
use bbs;
create table article
(
id int primary key auto_increment,
pid int,
rootid int,
title varchar(255),
cont text,
pdate datetime,
isleaf int
);
insert into article values (null, 0, 1, '蚂蚁大战大象', '蚂蚁大战大象', now(), 1);
insert into article values (null, 1, 1, '大象被打趴下了', '大象被打趴下了',now(), 1);
insert into article values (null, 2, 1, '蚂蚁也不好过','蚂蚁也不好过', now(), 0);
insert into article values (null, 2, 1, '瞎说', '瞎说', now(), 1);
insert into article values (null, 4, 1, '没有瞎说', '没有瞎说', now(), 0);
insert into article values (null, 1, 1, '怎么可能', '怎么可能', now(), 1);
insert into article values (null, 6, 1, '怎么没有可能', '怎么没有可能', now(), 0);
insert into article values (null, 6, 1, '可能性是很大的', '可能性是很大的', now(), 0);
insert into article values (null, 2, 1, '大象进医院了', '大象进医院了', now(), 1);
insert into article values (null, 9, 1, '护士是蚂蚁', '护士是蚂蚁', now(), 0);
package com.gdufe.bbs;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TreeShow {
public static void main(String[] args) {
TreeShow.show();
}
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost/bbs";
conn = DriverManager.getConnection(url, "root", "1234");
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public static void show() {
try {
Connection conn = TreeShow.getConnection();
Statement st = conn.createStatement();
String sql = "select * from article where pid=0";
ResultSet rs = st.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getInt("id") + rs.getString("cont"));
tree(conn, rs.getInt("id"), 0);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void tree(Connection conn, int id, int level) {
Statement st = null;
ResultSet rs = null;
StringBuffer preStr = new StringBuffer(" ");
for (int i = 0; i < level; i++) {
preStr.append(" ");
}
String sql = "select * from article where pid=" + id;
try {
st = conn.createStatement();
rs = st.executeQuery(sql);
while (rs.next()) {
System.out.println(preStr + "" + rs.getInt("id")
+ rs.getString("cont"));
if (rs.getInt("isleaf") != 0) {
tree(conn, rs.getInt("id"), level + 1);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
(注:为了方便代码理解,故意省去rs,st,conn的close()操作)
1蚂蚁大战大象
2大象被打趴下了
3蚂蚁也不好过
4瞎说
5没有瞎说
9大象进医院了
10护士是蚂蚁
6怎么可能
7怎么没有可能
8可能性是很大的