当用户在删除字段中输入错误的 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注入,你应该这样做。
如果您使用的是 JDBC,则可以检查#executeUpdate()
的结果以查看受影响的行数。如果它是零,那么你可以说这是一个错误的id
.
这是方法定义:
public int executeUpdate(java.lang.String sql)
返回值为:
指示受影响的行数的
int
,如果使用 DDL 语句,则0
。
在手头的程序中,您可以简单地执行以下操作:
int deleted = st.executeUpdate(query);
if (deleted == 0) {
JOptionPane.showMessageDialog(null, "Nothing to delete!");
return;
}