1. 程式人生 > >JAVAWEB實現增刪查改(圖書資訊管理)之刪除功能實現

JAVAWEB實現增刪查改(圖書資訊管理)之刪除功能實現

—————————————————————————————————————————————————————————— 

    刪除按鈕對應的servlet -->DeleteBooks.java  ↓

 1 package BookSystem.CRUD;
 2 import BookSystem.Other.DButil;
 3 
 4 
 5 import javax.servlet.ServletException;
 6 import javax.servlet.annotation.WebServlet;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 import java.io.IOException;
11 import java.sql.Connection;
12 import java.sql.PreparedStatement;
13 import java.sql.SQLException;
14 
15 @WebServlet("/books/del")
16 public class DeleteBooks extends HttpServlet {
17     @Override
18     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
19         //獲取id
20         int id=Integer.parseInt(req.getParameter("id"));
21         Connection connection=null;
22         PreparedStatement prsmt=null;
23         String sql;
24         try {
25             //獲取連線
26             connection=new DButil().getConnection();
27             //判斷:如果獲取一個id 就按id對應的資料刪除,否則刪除全部
28             if(id==-1){
29                 sql="delete from BookInfo ";
30 
31             }else {
32                 sql="delete from BookInfo  where book_id= "+id;
33             }
34             //執行sql語句
35             prsmt=connection.prepareStatement(sql);
36             prsmt.executeUpdate();
37         }catch (SQLException e){
38             e.printStackTrace();
39         }finally {
40             try {
41                 //關閉
42                 connection.close();
43                 prsmt.close();
44             } catch (SQLException e) {
45                 e.printStackTrace();
46             }
47 
48         }
49 
50         req.getRequestDispatcher("/books/lst").forward(req, resp);
51     }
52 
53 }

    刪除按鈕再index.jsp頁面,如下圖所示:↓

 

 

    注:該整個CRUD不展示效果圖,整體CSS應當有屬於自己的風