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

How to know if every queries executed successfully in loop?

假设我使用 PetaPoco 在循环中执行了一个更新查询,例如,

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

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

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
    }
}

通常 PetaPoco returns 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
}

Execute returns 受影响的行数。因此,如果您更新一行,如果成功,您将获得 1 作为 return 值,否则为 0(或错误)。

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;
}

所以 Execute 不会 return 1 表示成功,0 表示失败。它 returns 受影响的行数。例如,如果您执行此查询:DELETE FROM Table,您将删除此 table 的所有行,并且 return 值将是此 table 中的行数。所以这取决于逻辑和查询,如果 0 是失败或 1 是成功。

顺便说一句,此行为与 ADO.NET 方法一致,例如 SqlCommand.ExecuteNonQuery