4 回答
TA贡献1865条经验 获得超7个赞
首先,使用PreparedStatement填写参数而不是编写 SQL 字符串。
可以避免非常讨厌的错误(《Bobby Tables》XKCD 漫画中的 SQL 注入是如何工作的?)。所以
PreparedStatement stmt = con.prepareStatement("DELETE FROM info WHERE rollno=?");
stmt.setLong(1, Long.parseLong(rn.getText()));
int d = stmt.executeUpdate();
就您的问题而言:
该方法executeUpdate返回受影响的行数。
如果等于 0,则没有删除任何行。
if (d == 0)
{
JOptionPane.showMessageDialog(null,"This record does not exist");
// Return or thrown an exception or whatever to interrupt the operation
}
else
JOptionPane.showMessageDialog(null,"record deleted successfully!!!");
TA贡献1826条经验 获得超6个赞
showMessageDialog仅当变量值为正时才应执行,d即某些记录已从数据库中删除。例如
Class.forName("java.sql.DriverManager");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/stud","root","");
Statement stmt=con.createStatement();
String query="delete from info where rollno="+rn.getText();
int d = stmt.executeUpdate(query);
if(d>0){
JOptionPane.showMessageDialog(null,"record deleted successfully!!!");
}
rn.setText("");
TA贡献1868条经验 获得超4个赞
输入 rn:1 or 1=1并享受。使用PreparedStatements 将防止这种邪恶的SQL 注入。它还处理 SQL 字符串周围的撇号以及转义撇号和其他字符。
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/stud","root","");
String query="delete from info where rollno=?";
try (PreparedStatement stmt = con.prepareStatement(query)) {
stmt.setLong(1, Integer.parseLong(rn.getText()));
int d = stmt.executeUpdate();
if (d != 0) {
JOptionPane.showMessageDialog(null, "Record deleted successfully.",
JOptionPane.INFORMATION_MESSAGE);
}
}
此try-with-resources将确保stmt始终关闭
添加回答
举报