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
}