我正在尝试创建一个表单,卖家可以插入新项目,新类别和删除项目。现在我有DELETE的问题。 这是我的代码,如果有人知道如何解决它,请帮助。
String id = "42";
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/projekat","root","");
PreparedStatement prepared_statement = connection.prepareStatement("DELETE FROM artikli WHERE id= ? ;");
prepared_statement.setString(1, id);
int result_set = prepared_statement.executeUpdate();
if (result_set > 0)
{
System.out.println("Deleted");
}
else
{
System.out.println("Can't delete");
}
} catch (Exception ex) {
System.out.println(ex);
}
答案 0 :(得分:0)
试试这个:
String id = request.getParameter("id");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/projekat","root","");
PreparedStatement prepared_statement = null;
String strQuery = "DELETE FROM artikli WHERE id= ?";
prepared_statement = connection.prepareStatement(strQuery);
prepared_statement.setString(1, id);
int result_set = prepared_statement.executeUpdate();
if (result_set > 0)
{
// System.out.println(result_set);
response.sendRedirect("Prodaja2.jsp");
}
else
{
// System.out.println(result_set);
response.sendRedirect("Prodaja2.jsp?error=Can'tDelete");
}
} catch (Exception ex) {
out.print(ex);
} finally {
try {
stmtProd.close();
connection.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
在您的代码中,查询后面的分号可能会有冲突。并且也不要忘记关闭创建的finally块中的连接,因为它可能导致资源泄漏,即使用户注销,连接也将保持活动状态。
答案 1 :(得分:0)
这里有一个错误,就是你的语法
更改代码
PreparedStatement prepared_statement = connection.prepareStatement("DELETE FROM artikli WHERE id= ? ;");
到
PreparedStatement prepared_statement = connection.prepareStatement("DELETE FROM artikli WHERE id= ?");
如果没有其他错误,请检查id中的值,有可能为空值。