查询总是返回-1 不知道为什么。有人请解释一下。 count 的值始终为 -1。
string query = "SELECT COUNT(*) AS Emails FROM users";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@email", email);
try
{
connection.Open();
count = command.ExecuteNonQuery();
if (count > 0)
return "Something Wrong1";
}
catch
{
return "Something Wrong2";
}
return count + "Every thing ok";
}
最佳答案
那是因为ExecuteNonQuery
不返回查询结果,它只是在 SQL 服务器上执行它。返回值是受语句影响的行数,当语句不影响任何行时为 -1。 ExecuteNonQuery
(顾名思义)不是用于返回查询结果,而是用于运行更改数据的语句(例如 INSERT、DELETE、UPDATE)。文档状态:
For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. (...) For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.
你可以使用:
count = (int)command.ExecuteScalar();
获取您要查找的计数。 docs for ExecuteScalar
中也有一个示例.
关于c# - 计数总是返回 -1 SQL Server。 ASP.NET C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8962182/