修完功能开发完毕后,删除功能易如反掌。
首先在删除按钮上添加一个id:
<button type="button" class="btn btn-primary" id="delete">删除</button>
在jQuery中添加事件:
$("#delete").click(function() {
if (selectedId > -1) {
location.href = "stu?type=delete&id="+selectedId;
} else {
alert("请选择一条数据");
}
})
在后端StudentController.java中的doGet方法中添加一个选择分支:
else if (type.equals("delete")) {
delete(request, response);
}
并添加delete方法:
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 {
// 错误页面
}
}
在StudentDao类中添加delete方法,实现对数据库的表数据的删除:
public boolean delete(int id) {
int rs = 0;// 表示执行sql语句的结果
// jdbc 七个步骤
// 1.将数据库jar包拷贝到lib文件夹下
try {
// 2.加载驱动
Class.forName("com.mysql.jdbc.Driver");
// 3.建立连接
Connection conn = DriverManager
.getConnection("jdbc:mysql://localhost:3306/school_sk1?characterEncoding=utf-8", "root", "123456");
// 4.建立SQL执行器
Statement stat = conn.createStatement();
// 5.执行sql语句
String sql = "delete from student where id=" + id;
rs = stat.executeUpdate(sql);
// 6. 处理结果
// 7.关闭连接
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;
}