gpt4 book ai didi

java - MYSQL 删除语句不适用于 Java Servlet

转载 作者:行者123 更新时间:2023-11-29 07:38:21 25 4
gpt4 key购买 nike

我有一个网页,允许用户输入一个单词,当提交该单词时,它将从 mysql 数据库中删除。然而问题是该语句没有被执行。

我的表格:

<form id="rem1" action="removeGER" method="GET">
<input type="text" name="wordToRemoveGER" placeholder="Entry (GER)">
<input type="submit" id="removeBtnGER" value="Remove Entry">
</form>

我的servlet:

@WebServlet(name = "removeGER", urlPatterns = {"/removeGER"})
public class removeGER extends HttpServlet {

/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
String wordGER = request.getParameter("wordToRemoveGER");
PrintWriter out = response.getWriter();

out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Remove Word</title>");
out.println("</head>");
out.println("<body>");
Connection conn = null;

try {
// Database Checking Area
SimpleDataSource.init("/database.properties");
} catch (ClassNotFoundException ex) {
Logger.getLogger(Register.class.getName()).log(Level.SEVERE, null, ex);
}
try {
conn = SimpleDataSource.getConnection();
Statement stat = conn.createStatement();
//ResultSet result =
stat.executeQuery(" DELETE FROM `word` WHERE `word` = \""+wordGER+"\"");
out.println("<h2>You have successfully removed the word " + wordGER + "!</h2>");
} catch (SQLException ex) {
Logger.getLogger(removeID.class.getName()).log(Level.SEVERE, null, ex);
}
out.println("</body>");
out.println("</html>");
}

}

我知道正在从表单中正确检索字符串,并且我知道正在执行 try block 。问题似乎出在 mysql 语句本身。

最佳答案

您遇到以下问题:

  1. 您正在执行多个语句,但您的连接可能不允许这样做。
  2. 当执行多个语句时,应该使用 Statement#execute ,而不是Statement#executeUpdate
  3. 如果您需要向查询传递参数,请不要将其直接附加到 sql 中,这是 SQL Injection 的原因。攻击。请改用 PreparedStatement

为此,请通过将此参数添加到连接 URL 中,确保您的连接允许执行多个语句:allowMultiQueries=true

连接 URL 的外观示例:

jdbc:mysql://<server>:<port>/<database>?allowMultiQueries=true

如果使用 PreparedStatement,代码将是什么样子:

conn = SimpleDataSource.getConnection();
String sql = "SET SQL_SAFE_UPDATES = 0; DELETE FROM `word` WHERE `word` = ?";
PreparedStatement stat = conn.prepareStatement(sql);
stat.setString(1, wordGER);
stat.execute();
<小时/>

既然您使用了单个删除语句,那么您只需使用 PreparedStatement#executeUpdate 而不是 executeQuery

关于java - MYSQL 删除语句不适用于 Java Servlet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29923098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com