How to count rows in MySqlDataReader?

Petr picture Petr · Nov 14, 2009 · Viewed 15.5k times · Source

I have successfully switched my project from odbc.datareader to mysql.datareader. The problem is that with the first one /odbc datareader), the AffectedRows property retrieves the number of rows correctly even when it was pure query. But it doesn work with mysql.datareader, its -1 then. So I cannot see the way how to retrieve the number of rows, i.e. "result views". EDIT: I know its forward only reader, but what I dont understand is following: If a place a breakpoint to the line DBreader=command.ExecuteRader(), I can see that DBreader has - in the result view - as many objects as rows should be. How it comes that its known just after running? Thank you

Answer

Andomar picture Andomar · Nov 14, 2009

The reason DataReader doesn't contain the rowcount is that it can be very expensive to calculate. For example, say you execute a query that returns purchase orders that were entered this year and not deleted:

SELECT * FROM PurchaseOrders 
WHERE PurchaseDt > '2009-01-01'
AND IsDeleted = 0

And you use this query with a DataReader and read out the first 10 rows. SQL Server "streams" rows to the client as it requests them. Whenever you ask for another row, SQL Server will execute the next step of the query. So not even SQL Server knows about the total number of rows before you've actually read out all the rows.