c# - 计数总是返回 -1 SQL Server。 ASP.NET C#

标签 c# sql-server-2008

查询总是返回-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/

相关文章:

c# - Datagridview 组合框单元不会设置为 readonly = false

c# - 如何将整个可滚动 Canvas 另存为 Png

SQL Server 查询进行空控制

SQL 从表中选择不同的记录

c# - 从项目 2 的项目 1 中的类调用函数

c# - 使用 Linq 的 DbCommand?

sql-server-2008 - 使用 t sql 创建一个具有传染性的时间线集

sql-server - 运行存储过程时断开sql server

sql - 在 SQL Server 中结合使用条件运算符和 INTERSECT

c# - Linq-to-xml 按没有子元素的元素分组