Detailed tutorial on Java Web practice (XVIII) implementation of deletion function

Miss Zhu 2022-02-13 08:39:06 阅读数:61

detailed tutorial java web practice

         After repair and function development , The deletion function is easy .
         First, add a... On the delete button id:

<button type="button" class="btn btn-primary" id="delete"> Delete </button>

         stay jQuery Add events in :

$("#delete").click(function() {

if (selectedId > -1) {

location.href = "stu?type=delete&id="+selectedId;
} else {

alert(" Please select a piece of data ");
}
})

         On the back end StudentController.java Medium doGet Method :

else if (type.equals("delete")) {

delete(request, response);
}

         And add delete Method :

public void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

int id = Integer.parseInt(request.getParameter("id"));
StudentDao stuDao = new StudentDao();
boolean flag = stuDao.delete(id);
if (flag) {

response.sendRedirect("stu");
} else {

// Error page 
}
}

         stay StudentDao Class delete Method , Realize the deletion of table data in the database :

public boolean delete(int id) {

int rs = 0;// Indicates execution sql Result of statement 
// jdbc Seven steps 
// 1. Will database jar Package copy to lib Under the folder 
try {

// 2. The load driver 
Class.forName("com.mysql.jdbc.Driver");
// 3. Establishing a connection 
Connection conn = DriverManager
.getConnection("jdbc:mysql://localhost:3306/school_sk1?characterEncoding=utf-8", "root", "123456");
// 4. establish SQL actuator 
Statement stat = conn.createStatement();
// 5. perform sql sentence 
String sql = "delete from student where id=" + id;
rs = stat.executeUpdate(sql);
// 6. Processing results 
// 7. Close the connection 
conn.close();
} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {

// TODO Auto-generated catch block
e.printStackTrace();
}
return rs > 0;
}
copyright:author[Miss Zhu],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/02/202202130839043999.html