How to get number of rows from NpgsqlDataReader
I am trying to get the number of rows from the NpgsqlDataReader after using a select statement. The reason I am trying to check is to see if it has any data, a single row, or if it has multiple rows before working with the data. Any help will be g开发者_JS百科reatly appreciated.
This is being done in C# .NET 4
If the NpgsqlDataReader
inherits from DbDataReader
as other DataReaders do, you can check with
if (reader.HasRows) {...}
if there are any results. But I don't think that you can get the actual number of rows without looping through the reader....
From a bit of googling the NpgsqlDataReader would seem to be very similar to the sqldatareader. The sqldatareader does not have a built in way to get the row count. It would appear you would have to loop through and perform your own count if you wanted to get the rowcount.
If you only want a quick preview.
1.) does not have a result 2.) does have one result 3.) does have multiple results
you could execute the similar SQL Statement with a LIMITer. This should be very fast. And after that execution, you are going to retrieve the complete data.
example:
select * from [TABLE] where [CONDITION] LIMIT 2
if you get 0 rows, no result / if you get 1 row, one result / if you get 2 rows, multiple results
I would also like to get the number of rows for progress bar, but it seems I can't iterating twice is too much work for just showing progress ;)
You can create a proxy class, which is a child of NpgsqlDataReader
and where you re-implement iterator (extends IEnumerable
), which will implicitly iterate over first up to 2 rows if you either .Read()
or ask .CountClass
- then it will give those 2 from it's cache before directly reading the rest.
It depends on your use case, but in mine I put the results of the query into a List, then I can count the items on the list, it might not apply to your use case, but you can do a bunch of stuff on the results once you have it on a list.
精彩评论