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

来源:互联网 发布:ubuntu如何复制文件夹 编辑:程序博客网 时间:2024/05/22 06:27
<%@ 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>

原创粉丝点击