我的代码有一些错误,当我编写一个数据库中不存在的滚动号并按下删除按钮时,也会弹出一条消息:“已成功删除”。
实际上,我想通过连接java和MySQL来创建一个学生报告项目。所以我为delete按钮编写了代码,在这个代码中,如果写入并按下学生的滚动号,删除它将删除该学生的记录。
所以希望你能理解我的问题,并期待得到一个准确的答案。
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);
JOptionPane.showMessageDialog(null,"record deleted successfully!!!");
rn.setText("");发布于 2019-10-01 12:34:11
只有当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("");发布于 2019-10-01 12:29:54
首先,使用PreparedStatement填充参数,而不是组成SQL-字符串。
可以避免非常讨厌的错误(How does the SQL injection from the "Bobby Tables" XKCD comic work?)。所以
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!!!");发布于 2019-10-01 12:31:48
检查executeUpdate的结果是否大于0。如果是,则删除您的条目。
https://stackoverflow.com/questions/58184698
复制相似问题