1. 程式人生 > >運用遞迴 刪除父節點同事刪除子節點

運用遞迴 刪除父節點同事刪除子節點

<%@ 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>