运用递归 删除父节点同事删除子节点

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%@ page import="java.sql.*" %>
<%!
private void del(Connection conn,int id){     //定义了del函数
Statement stmt=null;
ResultSet rs=null;

try{
   stmt=conn.createStatement();
   String sql="select * from article where pid=" +id ;
   rs=stmt.executeQuery(sql);
   while(rs.next()){
     del(conn,rs.getInt("id"));
   }
   stmt.executeUpdate("delete from article where id="+id);    //递归删除子条目

}catch(SQLException e){
e.printStackTrace();
}finally{
   try {
    if(rs != null) {
     rs.close();
     rs = null;
    }
    if(stmt != null) {
     stmt.close();
     stmt = null;
    }
   } catch (SQLException e) {
    e.printStackTrace();
   }

}
%>
<%
String admin=(String)session.getAttribute("admin");
if(admin==null||!admin.equals("true")){
out.println("请登陆");
return;
}
%>
<%
int id= Integer.parseInt(request.getParameter("id"));
int pid= Integer.parseInt(request.getParameter("pid"));
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost/bbs?user=root&password=admin";
Connection conn = DriverManager.getConnection(url);

conn.setAutoCommit(false);     //设置不要自动提交
del(conn,id);
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery("select count(*) from article where pid="+pid);
rs.next();
int count=rs.getInt(1);
rs.close();
stmt.close();
if(count<=0){     // 判断要删除的节点的父节点是否为变成叶子节点
   Statement stmtUpdate=conn.createStatement();
   stmtUpdate.executeUpdate("update article set isleaf=0 where id ="+pid);
   stmtUpdate.close();
}
     conn.commit();    //提交SQL语句
     conn.setAutoCommit(true);    //回复conn的提交方式为自动提交
    conn.close();
%>
<html>
<head>
    <title>My JSP 'Delete.jsp' starting page</title>
</head>
<body>
   <a href="ShowArticleTree.jsp"><font size="7" color="#ff0080">删除成功,点击返回 </font><br></a>
</body>
</html>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值