Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read SQL Server COUNT from SqlDataReader

Tags:

c#

sql

sql-server

I'm trying to find the count for a table using C# SqlDataReader but I keep getting

invalid attempt to read when no data is present

My code:

string sql = "SELECT COUNT(*) FROM [DB].[dbo].[myTable]";

SqlCommand cmd = new SqlComman(sql, connectionString);
SqlDataReader mySqlDataReader = cmd.ExecuteReader();

int count = mySqlDataReader.GetInt32(0); // Here is where I get the error.

I know I have a valid connection to the database because I can read and write to it in many places, what's special about the COUNT(*) that I cannot read it properly? How do I get the int count to be populated?

like image 498
fifamaniac04 Avatar asked Oct 23 '13 16:10

fifamaniac04


People also ask

How do I get data from ExecuteReader?

To retrieve data using a DataReader, create an instance of the Command object, and then create a DataReader by calling Command. ExecuteReader to retrieve rows from a data source.

What does SqlDataReader return?

As explained earlier, the SqlDataReader returns data via a sequential stream. To read this data, you must pull data from a table row-by-row Once a row has been read, the previous row is no longer available.

Is there anything faster than SqlDataReader in net?

No. It is actually not only the fastest way - it is the ONLY (!) way. All other mechanisms INTERNALLY use a DataReader anyway.


1 Answers

You have to read it:

if (mySqlDataReader.Read()) {
  count = mySqlDataReader.GetInt32(0);
}

Alternatively, you can just use ExecuteScalar:

int count = (int)cmd.ExecuteScalar();

which is defined as:

Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.

like image 117
LarsTech Avatar answered Sep 20 '22 16:09

LarsTech