第四篇——删除商品信息
1、接口
boolean delete(int id);
2、dao
public boolean delete(int id) {
String sql="delete from product where id="+id;
int n=0;
try {
ps=ConnectionDatabase.getConnection().prepareStatement(sql);
n = ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return n>0;
}
3、测试
public void t() {
IProductDao dao = DaoFactory.getProductDao();
System.out.println(dao.delete(1));
}
4、servlet
private void deleteService(HttpServletRequest request, HttpServletResponse response) {
int id=Integer.parseInt(request.getParameter("id"));
try {
if (DaoFactory.getProductDao().delete(id)) {
request.getRequestDispatcher("OperatorServlet?op=query").forward(request, response);;
} else {
response.sendRedirect("main.jsp");
}
} catch (Exception e) {
}
}
5、测试
启动项目,在搜索栏输入
http://localhost:8081/ProductTest/OperatorServlet?op=delete&&id=5
6、主页
<html>
<head>
<title>product</title>
<script>
function fun( data){
decide=confirm("确认删除吗")
if(decide){
self.location.href="OperatorServlet?op=delete&&id="+data;
}
}
</script>
</head>
<body>
<center>
<table border="1">
<tr>
<th width="60">编号</th>
<th width="60">名称</th>
<th width="60">产地</th>
<th width="60">价格</th>
<th colspan="2" width="800">操作</th>
</tr>
<%
IProductDao dao = DaoFactory.getProductDao();
List<Product> list = dao.queryProduct();
for (Product p : list) {
%>
<tr>
<td><%=p.getId()%></td>
<td><%=p.getName()%></td>
<td><%=p.getAddr()%></td>
<td><%=p.getPrice()%></td>
<td><a href="#" onclick="fun(<%=p.getId()%>)">删除</a></td>
<td><a href="update.jsp?id=<%=p.getId() %>" >更新</a></td>
</tr>
<%
}
%>
</table>
</center>
</body>
</html>