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


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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值