JAVAWEB实现增删查改(图书信息管理)之删除功能实现

时间:2024-01-25 09:48:56

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

    删除按钮对应的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应当有属于自己的风格~