C# 成功删除记录时,ExecuteNonQuery 返回值 0
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9499043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ExecuteNonQuery returning value of 0 when successfully deleting a record
提问by nick gowdy
I have a slight issue in my C# code in Asp.net when deleting a row from sql server. I am using ExecuteNonQuery to determine which message I render to the page. If ExecuteNonQuery returns a 1 then I display success message. Where I am becoming stuck is I have the same logic for adding a record and updating a record and my code works fine. See below for the code.
从 sql server 中删除一行时,我在 Asp.net 中的 C# 代码中有一个小问题。我正在使用 ExecuteNonQuery 来确定我呈现给页面的消息。如果 ExecuteNonQuery 返回 1,则显示成功消息。我被卡住的地方是我有相同的逻辑来添加记录和更新记录,我的代码工作正常。请参阅下面的代码。
private void Delete_row(string ImageId)
{
string sSQL = "delete FROM dbo.Image_library_UK_temp where Image_id=" + ImageId;
using (SqlConnection dbConnection = new SqlConnection(app_settings.sql_conn_string_db))
{
try
{
//delete the row from db
dbConnection.Open();
SqlCommand command = new SqlCommand(sSQL, dbConnection);
command.CommandType = CommandType.Text;
command.CommandTimeout = 1024;
command.ExecuteNonQuery();
int rowsAffected = command.ExecuteNonQuery();
if (rowsAffected == 1)
{
messagepanel1.ShowSuccessMessage("The image " + txtImgTitle.Text + "has been deleted from the system.");
DisableValidation();
}
}
catch (Exception ex)
{
messagepanel1.ShowErrorMessage("Error: Deletion unsuccessful");
}
Session.RemoveAll();
generateTable(false);
}
}
Rows affected currently returns 0. This is a simple SQL statement so my sql is hard-coded in C# and I am not using a stored procedure.
受影响的行当前返回 0。这是一个简单的 SQL 语句,所以我的 sql 是用 C# 硬编码的,我没有使用存储过程。
Any ideas how I can make this work?
我有什么想法可以使这项工作?
采纳答案by penartur
You're executing the command twice.
您正在执行该命令两次。
command.ExecuteNonQuery();
int rowsAffected = command.ExecuteNonQuery();
The first line will delete the row and return 1, but you're ignoring the return value.
The second line will execute the DELETEstatement again, but it won't delete anything, because there is no more rows satisfying the given condition; thus, rowsAffectedwill be zero.
第一行将删除该行并返回 1,但您忽略了返回值。第二行将DELETE再次执行该语句,但不会删除任何内容,因为不再有满足给定条件的行;因此,rowsAffected将为零。
Also, your code is vulnerable to sql injections, as was already mentioned in comments. Consider using prepared statementsinstead.
此外,正如评论中已经提到的,您的代码容易受到 sql 注入的影响。考虑改用准备好的语句。

