*/
* Editor:Mr.Chen
* Time:2012-7-18 14:50
* Overview:
* 连接mysql中bbs数据库,并树状显示其中的内容
* */
import java.sql.*;
public class ArticleTree
{
public static void main(String[] args)
{
new ArticleTree().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:3306/bbs","root","root");
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();
}catch(SQLException e)
{
e.printStackTrace();
}finally
{
try
{
if(conn!= null){ conn.close(); conn=null;}
if(stmt!=null) {stmt.close();stmt=null;}
if(rs!=null) {rs.close();rs=null;}
}catch(SQLException e)
{e.printStackTrace();}
}
}
private void tree(Connection conn,int id,int level)//列出贴号为id的所有的跟帖及跟帖的所有跟帖
{
Statement stmt=null;
ResultSet rs=null;
String sql="select *from article where pid="+id;
StringBuffer strbuf=new StringBuffer("");
for(int i=0;i<level;i++)
{
strbuf.append(" ");
}
try
{
stmt=conn.createStatement();
rs=stmt.executeQuery(sql);
while(rs.next())
{
System.out.println(strbuf+rs.getString("cont"));
if(rs.getInt("isleaf")!=0)
tree(conn,rs.getInt("id"),level+1);
}
} catch (SQLException e)
{
e.printStackTrace();
}finally
{
try
{
if(stmt!=null) stmt.close();
if(rs!=null) rs.close();
}catch(SQLException e)
{
e.printStackTrace();
}
}
}
}