如何使用c#知道一条记录是否被删除

发布于 2024-12-08 15:17:51 字数 647 浏览 0 评论 0原文

我有下面的代码,其中对于每个序列号,我在 tblSerials 表中搜索并从那里删除它,但问题是,记录可能存在也可能不存在,所以我需要知道记录是否确实被删除,所以我可以更新另一个包含序列总数的表,其中 qty = qty - 1 (如果删除)。

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

所以我的问题是,是否有任何方法可以知道执行 ExecuteNonQuery() 后记录是否已从表中删除。

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 deleted, 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不羁少年 2024-12-15 15:17:51
 cmd.ExecuteNonQuery();

这将返回受影响的行数。

因此,如果您想知道有多少记录被删除,您需要

 int deletedRows = cmd.ExecuteNonQuery();
 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();
烙印 2024-12-15 15:17:51
int numRowsAffected = cmd.ExecuteNonQuery();
if (numRowsAffected > 0)
{
  // record deleted
}
else
{
  // record not deleted
}
int numRowsAffected = cmd.ExecuteNonQuery();
if (numRowsAffected > 0)
{
  // record deleted
}
else
{
  // record not deleted
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文