Question

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 greatly appreciated.

This is being done in C# .NET 4

Was it helpful?

Solution

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.

OTHER TIPS

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....

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top