gpt4 book ai didi

c# - 尽管有查询字符串,但在使用 sql COUNT 时 ExecuteNonQuery 返回 -1

转载 作者:行者123 更新时间:2023-11-30 13:44:31 27 4
gpt4 key购买 nike

由于某些原因,C# 中的 ExecuteNonQuery() 返回 -1,但当我单独运行查询时,该值返回所需的实际值。

例如:

try
{

var connString ="Data Source=ServerName;InitialCatalog=DatabaseName;Integrated Security=true;"
SqlConnection conn = new SqlConnection(connString);

SqlCommand someCmd = new SqlCommand("SELECT COUNT(*) FROM SomeTable");

someCmd.Connection = conn;

conn.Open();

var theCount = cmd.ExecuteNonQuery();

conn.Close();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}

当执行命令时,它返回 -1。虽然如果单独运行查询,

SELECT COUNT(*) FROM SomeTable;

如果被查询的表有 4 行,则该列返回计数为 4 的一行。

最佳答案

基于 MSDN :

For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.

您想返回受命令影响的行数并将其保存到 int 变量中,但是由于语句的类型是 select 所以它返回 -1.

解决方案:如果您想获取受 SELECT 命令影响的行数并将其保存到一个 int 变量中,您可以使用 ExecuteScalar .

var theCount = (int)cmd.ExecuteScalar();

关于c# - 尽管有查询字符串,但在使用 sql COUNT 时 ExecuteNonQuery 返回 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38060489/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com