java中删除查询的验证

java中删除查询的验证,java,sql,validation,Java,Sql,Validation,我在验证我的删除查询时遇到问题,我键入的任何内容,即使数据不在我的数据库中,它也会继续删除,并表示成功。如果用户键入数据库中不存在的数据,我希望它出错。这是我的密码: try{ System.out.println("Enter record you want to delete: "); frail = scn.nextLine(); }catch(Exception ee){ System.out.println(ee.getMessage()); } tr

我在验证我的删除查询时遇到问题,我键入的任何内容,即使数据不在我的数据库中,它也会继续删除,并表示成功。如果用户键入数据库中不存在的数据,我希望它出错。这是我的密码:

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
} 

您可以捕获的返回值如下所示:

int rowAffacted = psII.executeUpdate();
if (rowAffacted != 0) {
     System.out.println("Deleted!");
}
Javadoc for executeUpdate的返回值为

either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing
executeUpdate()
返回更改的行数,或者在不影响行的情况下返回
0
,因此在您的情况下,您可以执行以下操作:

int alteredRows=psII.executeUpdate();
if(alteredRows==0)
{
    System.out.println("No rows deleted");
}
else
{ 
    System.out.println(alteredRows +"rows deleted");
}

您好,我在这里使用您的代码,但即使我删除数据库中的数据,它仍然取决于是否显示“未删除行”
executeUpdate()
返回的值是多少如果您将
alteredRows
的值作为
1
它如何进入
如果
噢,对不起,executeUpdate()即使我删除了1行,也始终返回0。在那里,我使用了该代码并添加了else{System.out.println(“不受影响的行”);},但即使我删除了数据库中的数据,它仍然会出现else@tinker101你能在两种情况下都显示无效果的箭头吗?使用no delete和delete?您好,我使用这个,但即使有受影响的行,它仍然落在no AffectedRows上。如何显示noOfAffectedRows?我删除了一行,但它仍然落在不受影响的位置Rows@tinker101
System.out.println(noOfAffectedRows)
这样你就可以看到如果没有记录被删除,而有记录被删除,noOfAffectedRows
是否不同了。哦,对不起。上面写着0,但我删除了1行。