Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve the count of the number of rows in asp.net mvc from sql database?

Tags:

c#

mysql

asp.net

I am trying to print something if the number of rows returned is more than 0 based on a query:

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();
}

How can I find the number of rows returned?

like image 525
Spider Man Avatar asked Jan 05 '23 00:01

Spider Man


2 Answers

Your query always return one row even no rows exists. It will return 0 if no rows exists for your WHERE condition

Use SqlCommand.ExecuteScalar Method ()

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();
}

ScalarValue will return first column of first row of query result. So for your query this is more effective method to retrieve information you need.

like image 119
Fabio Avatar answered Jan 07 '23 14:01

Fabio


You can do this, Because ExecuteNonQuery - returns the number of rows affected.

int numberOfRecords = cmd.ExecuteNonQuery();
if (numberOfRecords  > 0) 
{
  Console.WriteLine("Returned more than 0 rows");
}
else
{
    Console.WriteLine("Did not return more than 0 rows");
}
like image 26
Sajeetharan Avatar answered Jan 07 '23 14:01

Sajeetharan