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?
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.
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.
No. It is actually not only the fastest way - it is the ONLY (!) way. All other mechanisms INTERNALLY use a DataReader anyway.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With