刪除資料這部分比較多,於是我打算分2天完成
我的預想是:有一個頁面顯示出所有的資料,跟之前的查詢資料相同,還有一個label可以輸入想刪除的資料,一樣有一個返回首頁的按鈕
新建一個DeleteData的Class,裡面會有一個doPost處理我們要刪除的資料,"DeleteData"Method裡面的preparedstatement是之前介紹的delete... where =?
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
String studentNumber = request.getParameter("number");
if (studentNumber != null) {
deleteData(Integer.parseInt(studentNumber));
}
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>刪除成功</h1>");
out.println("<a href=\"http://localhost:8080/forms/DeleteData.jsp\">返回</a>");
out.println("</body></html>");
}
public static void deleteData(int number) {
String deleteSQL = "DELETE FROM student_information WHERE number = ?";
try (Connection connection = DriverManager.getConnection(JDBC_url, JDBC_user, JDBC_password);
PreparedStatement preparedStatement = connection.prepareStatement(deleteSQL)) {
preparedStatement.setInt(1, number);
int rowsDeleted = preparedStatement.executeUpdate();
if (rowsDeleted > 0) {
System.out.println("Successfully deleted student with number: " + number);
} else {
System.out.println("No student found with number: " + number);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
刪除成功之後會有一個按鈕可以返回首頁,還有處理如果沒有辦法顯示資料的問題,Class裡面處理完之後就剩下.jsp檔案了,這部份我們明天再分享!