开发者

How to know if a record was deleted using c#

开发者 https://www.devze.com 2023-04-10 07:24 出处:网络
I have the below code, in which for every serialnumber I search in tblSerials table and delete it from there, but the thing is that, the record may or may not be there, so I need to know if the record

I have the below code, in which for every serialnumber I search in tblSerials table and delete it from there, but the thing is that, the record may or may not be there, so I need to know if the record was actually de开发者_高级运维leted, so I can update another table that has the total qty of serials, with qty = qty - 1 (in case of deletion).

SqlConnection conn = new SqlConnection(connString);
for (int i = 0; i <= aSNs.Count()-1; i++)
{
    string query = "delete from tblSerials where SerialNumber='" +aSNs[i]+ "'";
    SqlCommand cmd = new SqlCommand(query, conn);

    try
    {
        conn.Open();
        cmd.ExecuteNonQuery(); 
    }
    catch (Exception ex)
    {
        throw (ex);
    }
    finally
    {
        cmd.Dispose();
        conn.Close();
    }
}

So my question is, if there is any way to know if a record was either deleted or not from a table once ExecuteNonQuery() took place.


 cmd.ExecuteNonQuery();

This returns the number of rows affected.

So if you want to know how many records were deleted you need to

 int deletedRows = cmd.ExecuteNonQuery();


int numRowsAffected = cmd.ExecuteNonQuery();
if (numRowsAffected > 0)
{
  // record deleted
}
else
{
  // record not deleted
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号