我编写了一个方法,它将尝试根据主键id从db表中删除一行。我遇到的问题是try块总是返回“Success”,即使记录已被删除/或它不存在。
public string delete_visit(int id)
{
string deleteResponse = null;
string cnn = ConfigurationManager.ConnectionStrings[connname].ConnectionString;
using (SqlConnection connection = new SqlConnection(cnn))
{
string SQL = string.Empty;
SQL = "DELETE FROM [" + dbname + "].[dbo].[" + tbname + "] WHERE VisitorNumber = @IDNumber ";
using (SqlCommand command = new SqlCommand(SQL, connection))
{
command.Parameters.Add("@IDNumber", SqlDbType.Int);
command.Parameters["@IDNumber"].Value = id;
try
{
connection.Open();
command.ExecuteNonQuery();
deleteResponse = "Success";
}
catch (Exception ex)
{
deleteResponse = "There was a problem deleting the visit from the database. Error message: " + ex.Message;
}
}
}
return deleteResponse;
}
我希望能够判断该行是否受到影响。我可以在SQL Server Management Studio中执行此操作,如下所示:
DELETE FROM Visits
WHERE VisitorNumber=88;
IF @@ROWCOUNT = 0
PRINT 'Warning: No rows were updated';
所以我想知道如何将@@ ROWCOUNT位插入到我的c#中,以便我可以判断该行是否已被删除?
感谢
答案 0 :(得分:7)
ExecuteNonQuery()
returns an int
,表示受影响的行数。
所以:
int rowsAffected = command.ExecuteNonQuery();
if (rowsAffected == 0)
{
deleteResponse = "No rows affected";
}
问题是这个数字可能会根据查询的实际情况而受到影响。执行触发器或调用存储过程可能会弄乱输出,从而更改受影响的行数。如果你真的必须,那么首先执行一个查询,检查具有给定ID的记录是否存在。