我在验证我输入的任何删除查询时遇到问题,即使数据不在我的数据库中,它也会不断删除,它表示成功,如果用户输入数据库中不存在的数据,我希望它出现错误。这是我的代码:
try{
System.out.println("Enter record you want to delete: ");
frail = scn.nextLine();
}catch(Exception ee){
System.out.println(ee.getMessage());
}
try{
stmt = conn.createStatement();
String sqlII = "delete from tbl_test where test_name = ?";
PreparedStatement psII = conn.prepareStatement(sqlII);
psII.setString(1, frail);
psII.executeUpdate();
int rowAffacted = psII.executeUpdate();
if (rowAffacted != 0) {
System.out.println("Deleted!");
}else{
System.out.println("No Affected Rows!");
}
}
catch(Exception eer){
System.out.println(eer.getMessage());
}
最佳答案
psII.executeUpdate();
返回一个 int。如果这些值为零,则不会删除任何行,因此您可以看到该用户存在不在数据库中,并且可以显示错误。用户是否正确,该值应大于零。
int noOfAffectedRows =psII.executeUpdate();
if (noOfAffectedRows = 0){
//show Error
}
关于java - java中删除查询的验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27542224/