写一个servlet根据form表单提交的title删除数据库中留言
时间: 2024-02-28 19:53:56 浏览: 66
Servlet_JSP 连接数据库
5星 · 资源好评率100%
好的,我可以为您提供一个参考代码,您可以根据您的具体需求进行修改:
```java
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;
@WebServlet("/deleteMessage")
public class DeleteMessageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String DB_URL = "jdbc:mysql://localhost:3306/mydb";
private static final String DB_USER = "root";
private static final String DB_PASSWORD = "root";
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String title = request.getParameter("title");
Connection conn = null;
PreparedStatement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
String sql = "DELETE FROM messages WHERE title = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, title);
int rowsDeleted = stmt.executeUpdate();
if (rowsDeleted > 0) {
response.getWriter().println("Message deleted successfully");
} else {
response.getWriter().println("No message found with the title " + title);
}
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
response.getWriter().println("Error deleting message: " + e.getMessage());
} finally {
try {
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
在上面的代码中,我们首先从请求中获取要删除的留言的标题,然后使用 JDBC 连接到 MySQL 数据库,并执行一个 DELETE SQL 语句,以删除具有指定标题的留言。在删除操作完成后,我们向客户端发送一条消息,指示操作是否成功。
请注意,这只是一个示例代码,您需要根据您的具体需求进行修改。您需要替换 `DB_URL`、`DB_USER` 和 `DB_PASSWORD` 常量的值,以反映您的数据库连接参数。同样,您需要在您的表中使用正确的列名来代替 `messages` 表和 `title` 列。
阅读全文