`

递归显示论坛树状帖子、删除帖子

    博客分类:
  • J2SE
SQL 
阅读更多
1、关于递归方法的使用(2个):

    (1)用递归展现树状的帖子,代码如下:

public void tree(List<Article> articles, Connection conn, int id, int grade) {
 String sql = "select * from article where pid = " + id;
 Statement stmt = DB.createStmt(conn);
 ResultSet rs = DB.executeQuery(stmt, sql);
 try {
  while (rs.next()) {
   Article a = new Article();
   a.initFromRs(rs);
   a.setGrade(grade);
   articles.add(a);
   if (!a.isIsleaf()) {
    tree(articles, conn, a.getId(), grade+1);
   }
  }
 } catch (SQLException e) {
  e.printStackTrace();
 } finally {
  DB.close(rs);
  DB.close(stmt);
 }
}

//调用上面的方法
List<Article> articles = new ArrayList<Article>();
Connection conn = DB.getConn();
tree(articles , conn, 0, 0);
DB.close(conn);

 (2)用递归方法删除帖子:

         public void delete (Connection conn, int id, boolean isLeaf) {
 if (!isLeaf) {
  String sql = "select * from article where pid = " + id;
  Statement stmt = DB.createStmt(conn);
  ResultSet rs = DB.executeQuery(stmt, sql);
  try {
   while (rs.next()) {
    delete(conn, rs.getInt("id"),rs.getInt("isleaf")==0);
   }
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   DB.close(rs);
   DB.close(stmt);
  }
 }
 //delete self
 DB.executeUpdate(conn,"delete from article where id = " + id);
 
}


int id = Integer.parseInt(request.getParameter("id"));
int pid = Integer.parseInt(request.getParameter("pid"));
String url = request.getParameter("from");
boolean isLeaf = Boolean.parseBoolean(request.getParameter("isleaf"));
ResultSet rs = null;
Statement stmt = null;
Connection conn = DB.getConn();
boolean autoCommit = true;


 autoCommit = conn.getAutoCommit();
//设置事物为手动提交
 conn.setAutoCommit(false);
//调用删除方法。
 delete(conn, id, isLeaf);
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics