4 回答

TA貢獻(xiàn)1865條經(jīng)驗 獲得超7個贊
首先,使用PreparedStatement填寫參數(shù)而不是編寫 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返回受影響的行數(shù)。
如果等于 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貢獻(xiàn)1826條經(jīng)驗 獲得超6個贊
showMessageDialog僅當(dāng)變量值為正時才應(yīng)執(zhí)行,d即某些記錄已從數(shù)據(jù)庫中刪除。例如
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貢獻(xiàn)1868條經(jīng)驗 獲得超4個贊
輸入 rn:1 or 1=1并享受。使用PreparedStatements 將防止這種邪惡的SQL 注入。它還處理 SQL 字符串周圍的撇號以及轉(zhuǎn)義撇號和其他字符。
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始終關(guān)閉
添加回答
舉報