如何从sql数据库中检索asp.net mvc中的行数?

Spi*_*Man 4 c# mysql asp.net

我试图打印一些东西,如果根据查询返回的行数大于0:

using (SqlConnection con = new SqlConnection("ConnectionString")){
  con.Open();
  string query = "SELECT COUNT(*) FROM Some_Table WHERE Val > 5";
  SqlCommand cmd = new SqlCommand(query, con);
  cmd.ExecuteNonQuery(); // get the value of the count
  if (count > 0) 
  {
    Console.WriteLine("Returned more than 0 rows");
  }
  else
  {
    Console.WriteLine("Did not return more than 0 rows");
  }
  Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)

如何找到返回的行数?

Fab*_*bio 5

即使没有行,您的查询也会返回一行.如果您的WHERE条件不存在任何行,它将返回0

使用SqlCommand.ExecuteScalar方法()

using (var con = new SqlConnection("ConnectionString"))
{
  con.Open();
  string query = "SELECT COUNT(*) FROM Some_Table WHERE Val > 5";

  using (var cmd = new SqlCommand(query, con))
  {
      int rowsAmount = (int)cmd.ExecuteScalar(); // get the value of the count
      if (rowsAmount > 0) 
      {
          Console.WriteLine("Returned more than 0 rows");
      }
      else
      {
          Console.WriteLine("Did not return more than 0 rows");
      }

      Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)

ScalarValue将返回第一行查询结果的第一列.因此,对于您的查询,这是检索所需信息的更有效方法.