您的位置:首页 > 其它

ArticleTree

2015-08-14 22:12 267 查看
*/

* 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();
}
}
}


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: