我想从数据库中删除一条记录。代码运行良好,但即使存在特定 id 的记录,该消息也会返回 id not found in database
。请帮助我改进我的代码,以便在数据库中找不到 id 时显示单独的消息。我已附上我的输出。正如你可以看到 id=19 我在数据库中,但是当我删除 id=19 时,该特定 id 记录将从数据库中删除,但会弹出消息说在数据库中找不到 id。
try {
String s = TUID.getText( );
Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/mysql", "root", "root" );
Statement st = con.createStatement( );
String r = "delete from mysql57.addressbook where iid = "+s;
PreparedStatement preparedStatement = con.prepareStatement( r );
preparedStatement.executeUpdate( );
int rows = preparedStatement.executeUpdate();
if(rows == 0)
{ JOptionPane.showMessageDialog( f, "ID NOT FOUND IN DATABASE");
}
else{
JOptionPane.showMessageDialog( f, "DELETED FROM DATABASE" );
}
}
}
catch (Exception ex) {
JOptionPane.showMessageDialog( f,ex );
}
最佳答案
executeUpdate()
方法返回受影响的行数。如果没有删除任何行,它会返回0
(自然)。
所以...
int rows = preparedStatement.executeUpdate();
if(rows == 0)
...
else
...
您还应该正确使用 PreparedStatement
,并将 + s
更改为占位符(令人惊讶的是,每个教程似乎都滥用 PreparedStatement
并教导坏习惯)。
关于java - 没有从数据库中删除的消息对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47316443/