【问题标题】:Select query to get data from SQL Server选择查询以从 SQL Server 获取数据
【发布时间】:2014-11-02 14:08:47
【问题描述】:

我正在尝试在我的 C# 代码中运行 SQL Select 查询。但我总是在

上得到 -1 输出
int result = command.ExecuteNonQuery();

但是,如果我使用 deleteinsert 使用同一张表...

ConnectString 也可以。

请检查以下代码

SqlConnection conn = new SqlConnection("Data Source=;Initial Catalog=;Persist Security Info=True;User ID=;Password=");
conn.Open();

SqlCommand command = new SqlCommand("Select id from [table1] where name=@zip", conn);

//command.Parameters.AddWithValue("@zip","india");
int result = command.ExecuteNonQuery();

// result gives the -1 output.. but on insert its 1
using (SqlDataReader reader = command.ExecuteReader())
{
    // iterate your results here
    Console.WriteLine(String.Format("{0}",reader["id"]));
}

conn.Close();

查询在 SQL Server 上运行良好,但我不明白为什么只有选择查询不起作用。

所有其他查询都在工作。

【问题讨论】:

  • 为什么要执行两次命令?
  • 正是 Marc 并试图在不执行 Read() 方法的情况下读取记录。
  • 帮自己一个忙,使用存储过程。

标签: c# sql asp.net sql-server


【解决方案1】:

SqlCommand.ExecuteNonQuery 方法

您可以使用 ExecuteNonQuery 执行目录操作(例如,查询数据库的结构或创建表等数据库对象),或者通过执行 UPDATE、INSERT 或删除语句。 尽管 ExecuteNonQuery 不返回任何行,但任何输出参数或映射到参数的返回值都会填充数据。 对于 UPDATE、INSERT 和 DELETE 语句,返回值是受命令影响的行数。当正在插入或更新的表上存在触发器时,返回值包括受插入或更新操作影响的行数以及受一个或多个触发器影响的行数。对于所有其他类型的语句,返回值为 -1。如果发生回滚,返回值也是-1。

SqlCommand.ExecuteScalar 方法 针对连接执行 Transact-SQL 语句并返回受影响的行数。

所以不要。 SELECT 语句返回的语句必须使用 ExecuteScalar 方法。

参考:http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery(v=vs.110).aspx

所以试试下面的代码:

SqlConnection conn = new SqlConnection("Data Source=;Initial Catalog=;Persist Security Info=True;User ID=;Password=");
conn.Open();

SqlCommand command = new SqlCommand("Select id from [table1] where name=@zip", conn);
command.Parameters.AddWithValue("@zip","india");
 // int result = command.ExecuteNonQuery();
using (SqlDataReader reader = command.ExecuteReader())
{
  if (reader.Read())
  {
     Console.WriteLine(String.Format("{0}",reader["id"]));
   }
}

conn.Close();

【讨论】:

  • 没有必要关闭reader,并且reader.Close();这一行是多余的,因为reader将被using (SqlDataReader reader = ...关闭
  • SqlCommand.ExecuteScalar 不返回受影响的行数。它返回“结果集中第一行的第一列,或空引用”,所以我相信它最适合这个问题。
【解决方案2】:

根据 MSDN

http://msdn.microsoft.com/ru-ru/library/system.data.sqlclient.sqlcommand.executenonquery(v=vs.110).aspx

结果是受影响的行数,并且由于您的查询是select没有行受到影响(即插入、删除或更新)无论如何。

如果您想返回查询的单行,请使用ExecuteScalar() 而不是ExecuteNonQuery()

  int result = (int) (command.ExecuteScalar());

但是,如果您希望返回 许多行,则ExecuteReader() 是唯一的选择:

  using (SqlDataReader reader = command.ExecuteReader()) {
    while (reader.Read()) {
      int result = reader.GetInt32(0);

      ...
    }
  }

【讨论】:

    【解决方案3】:

    您可以使用ExecuteScalar() 代替ExecuteNonQuery() 来获得单个结果 像这样使用它

    Int32 result= (Int32) command.ExecuteScalar();
    Console.WriteLine(String.Format("{0}", result));
    

    它将执行查询,并返回查询返回的结果集中第一行的第一列。其他列或行将被忽略。

    由于您只想要一行作为回报,请从您的代码中删除对 SqlDataReader 的这种使用

    using (SqlDataReader reader = command.ExecuteReader())
    {
        // iterate your results here
        Console.WriteLine(String.Format("{0}",reader["id"]));
    }
    

    因为它会再次执行您的命令并影响您的页面性能。

    【讨论】:

      【解决方案4】:

      这是设计使然。

      http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery(v=vs.110).aspx

      对于 UPDATE、INSERT 和 DELETE 语句,返回值是受命令影响的行数。当正在插入或更新的表上存在触发器时,返回值包括受插入或更新操作影响的行数以及受一个或多个触发器影响的行数。对于所有其他类型的语句,返回值为 -1。如果发生回滚,返回值也是-1。

      【讨论】:

        【解决方案5】:

        你还必须添加参数@zip

         SqlConnection conn = new SqlConnection("Data Source=;Initial Catalog=;Persist Security Info=True;User ID=;Password=");
              conn.Open();
              SqlCommand command = new SqlCommand("Select id from [table1] where name=@zip", conn);
              //
            // Add new SqlParameter to the command.
            //
              command.Parameters.AddWithValue("@zip","india");
              int result = (Int32) (command.ExecuteScalar());
              using (SqlDataReader reader = command.ExecuteReader())
              {
                  // iterate your results here
               Console.WriteLine(String.Format("{0}",reader["id"]));
        
              }
              conn.Close();
        

        【讨论】:

          【解决方案6】:

          您应该使用ExecuteScalar()(返回第一行第一列)而不是ExecuteNonQuery()(返回受影响的行数)。

          您应该参考differences between executescalar and executenonquery了解更多详情。

          希望对你有帮助!

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-10-30
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-03-14
            • 1970-01-01
            相关资源
            最近更新 更多