如何知道每个查询是否在循环中成功执行?

时间:2016-05-09 10:44:37

标签: c# foreach petapoco

假设我已使用 PetaPoco 执行循环更新查询,

foreach (var obj in mainObject) {
   db.Execute("update Table set Column = @0 where C1=@1 and C2 =@2", Column1, obj.data1, obj.data2);
}

如何知道每个查询是否已成功执行?

3 个答案:

答案 0 :(得分:5)

Execute返回受影响的行数。因此,如果您更新一行,如果成功则返回<body onload='document.form1.newpassword.focus()'> <form name="form1" action="" method="post" id="form1" onsubmit="return CheckPassword(document.form1.newpassword)"> <table width="388" align="center"></br> <tr> <td align="right">Enter Username</td> <td align="center"> <input type="username" name="username" value="<?php echo ucwords($_SESSION['username']); ?> " class="TxtBox" disabled="disabled" /> </td> </tr> <tr> <td colspan="2"> <h5>Input Password and Submit [6 to 20 characters which contain at least one numeric digit, one uppercase and one lowercase letter]</h5> </td> </tr> <tr> <td align="right">New Password</td> <td align="center"> <input type="password" name="newpassword" class="TxtBox" /> </td> </tr> <tr> <td align="center"> <div align="center"> <input type="submit" name="submit" value="submit" /> </div> </td> </tr> </table> </form> </body> 作为返回值,否则为0(或错误)。

1

因此bool allSucceeded = true; foreach (var obj in mainObject) { int updated = db.Execute("update Table set Column = @0 where C1=@1 and C2 =@2", Column1, obj.data1, obj.data2); bool succeed = updated != 0; if(!succeed) allSucceeded = false; } 不会返回1表示成功,0表示失败。它返回受影响的行数。例如,如果您执行此查询:Execute您将删除此表的所有行,返回值将是此表中的行数。所以它取决于逻辑和查询,如果0是失败或1是成功。

顺便说一下,这种行为与像SqlCommand.ExecuteNonQuery这样的ADO.NET方法一致。

答案 1 :(得分:4)

通常PetaPoco会返回 1 或更高,如果单个查询成功执行,或者意味着是否有任何行受影响, 0 如果失败。

使用此方案,您可以通过在循环中添加这些值来跟踪这些值,例如:

List<int> checkSuccess = new List<int>(); //To trace the value returned by execute query

foreach (var obj in mainObject) {
    int updated = db.Execute("update Table set Column = @0 where C1=@1 and C2 =@2", Column1, obj.data1, obj.data2);
    checkSuccess.Add(updated);
}

if (checkSuccess.All(i => i >= 1))
{
    //Your every queries has been updated successfully
}

答案 2 :(得分:0)

foreach (var obj in mainObject) 
{
    var result = db.Execute("update Table set Column = @0 where C1=@1 and C2 =@2", Column1, obj.data1, obj.data2);
    if (result < 1)
    {
     //not ok
    }
}