package demo; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class DeleteCustomer */ @WebServlet("/delete.do") public class DeleteCustomer extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public DeleteCustomer() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response) */ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String CustomerID =request.getParameter("id");//获取浏览器输入的参数 //设置数据库连接参数 String url="jdbc:mysql://localhost:3306/库名?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT"; String user = "用户名"; String password="密码"; //加载数据库驱动 try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } try(Connection connection =DriverManager.getConnection(url, user, password)){//连接数据库 //where一定有指明什么地方 //sql语句删除记录 where表示条件,customers为表名 String sql = "delete from customers where CustomerID= ?;"; PreparedStatement statement = connection.prepareStatement(sql);//预处理sql语句 //填入预处理语句得参数 statement.setInt(1, Integer.parseInt(CustomerID)); int value = statement.executeUpdate();//executeUpdate执行修改,将修改的个数传给value statement.close();// 关闭statement,释资源 }catch(SQLException e) { e.printStackTrace(); } request.setAttribute("msg", "删除成功!"); request.getRequestDispatcher("queryalldata.jsp").forward(request, response);//跳转到查询所有得服务程序 } }