当用户在删除字段中输入错误的 ID 时,我希望弹出一个错误。但是即使输入了错误的id,查询仍然进行,但是没有数据被删除。这是我的代码:
String value = jTextField19.getText();
if (value == null || "".equals(value)) {
JOptionPane.showMessageDialog(null, "The field is blank!");
} else {
theQuery("DELETE FROM inventorydb WHERE item_id=('"+jTextField19.getText()+"') AND item_id IS NOT NULL");
}
theQuery
方法:
private void theQuery(String query) {
Connection con = null;
Statement st = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/inventory", "root", "");
st = con.createStatement();
st.executeUpdate(query);
JOptionPane.showMessageDialog(null, "Done!");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null,"Error!");
}
}
最佳答案
首先:不要永远直接根据用户输入构建 SQL 查询,而是使用准备好的语句。如果您不了解 SQL 注入(inject),您应该了解一下。
如果您使用的是 JDBC,则可以检查 #executeUpdate()
的结果以查看受影响的行数。如果它是零,那么你可以说它是一个错误的 id
。
这是方法定义:
public int executeUpdate(java.lang.String sql)
返回值为:
An
int
that indicates the number of rows affected, or0
if using a DDL statement.
在手头的程序中,您可以简单地执行以下操作:
int deleted = st.executeUpdate(query);
if (deleted == 0) {
JOptionPane.showMessageDialog(null, "Nothing to delete!");
return;
}
关于java - 如何查看数据库是否删除成功?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37413538/