import java.sql.*; //jdbc.jar
public class ArticleTree { public static void main(String[] args) { new ArticleTree().show(); }
//方法show,显示建立的树
public void show() {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager
.getConnection("jdbc:mysql://localhost/bbs?user=root&password=root"); //建立bbs数据库的Connection conn
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from article where pid = 0");
while(rs.next()){
System.out.println(rs.getString("cont"));
tree(conn, rs.getInt("id"), 1);
}
} catch(ClassNotFoundException e) {
e.printStackTrace(); //ClassNotFoundException,无法找到指定的类异常
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(rs != null) {
rs.close();
rs = null;
}
if(stmt != null) {
stmt.close();
stmt = null;
}
if(conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//方法tree建立树,Database Connection conn已建立
private void tree(Connection conn, int id, int level) {
Statement stmt = null;
//Java执行数据库操作的一个重要接口Statement,用于发送要执行的SQL语句
ResultSet rs = null;
//database结果集的数据表ResultSet,为指针,方法next可使其移动下一行
//当对字符串进行修改的时候,需要使用 StringBuffer类
//和 String 类不同的是,StringBuffer类的对象能够被多次的修改
StringBuffer strPre = new StringBuffer("");
for(int i=0; i<level; i++) {
strPre.append(" "); //方法append,将指定的字符串(4个空格)追加到此字符序列
//建树格式
}
//try{} catch{} finally{}捕捉异常,try语句出现异常则执行catch语句
try {
stmt = conn.createStatement();
String sql = "select * from article where pid = " + id;//要执行的SQL语句
rs = stmt.executeQuery(sql);
while(rs.next()) {
System.out.println(strPre + rs.getString("cont"));
//获取rs指向当行的cont列的值
if(rs.getInt("isleaf") != 0)
tree(conn, rs.getInt("id"), level + 1);//增加一层建立子树
}
} catch (SQLException e) {
e.printStackTrace(); //SQLException,操作数据库异常
//类SQLException的方法printStackTrace,在命令行打印异常信息在程序中出错的位置及原因
} finally {
try {
if(rs != null) {
rs.close();
rs = null;
}
if(stmt != null) {
stmt.close();
stmt = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}//关闭,释放内存
}
复制代码
}