如何从 NpgsqlDataReader 获取行数
我试图在使用 select 语句后从 NpgsqlDataReader 获取行数。我试图检查的原因是在处理数据之前查看它是否有任何数据、单行或者是否有多行。任何帮助将不胜感激。
这是在 C# .NET 4 中完成的
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果
NpgsqlDataReader
像其他DataReader一样继承自DbDataReader
,您可以检查是否有任何结果。但我不认为你可以在不循环阅读器的情况下获得实际的行数......
If the
NpgsqlDataReader
inherits fromDbDataReader
as other DataReaders do, you can check withif there are any results. But I don't think that you can get the actual number of rows without looping through the reader....
通过谷歌搜索,NpgsqlDataReader 似乎与 sqldatareader。 sqldatareader 没有内置的方法来获取行数。 它会出现 如果您想获得行计数,则必须循环并执行自己的计数。
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.
如果您只想快速预览。
1.) 没有结果
2.) 确实有一个结果
3.) 确实有多个结果,
您可以使用 LIMITer 执行类似的 SQL 语句。这应该是非常快的。执行之后,您将检索完整的数据。
示例:
select * from [TABLE] where [CONDITION] LIMIT 2
如果得到 0 行,则没有结果 /
如果你得到 1 行,一个结果 /
如果你得到 2 行,多个结果
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
我还想获取进度条的行数,但似乎我无法迭代两次,这对于仅显示进度来说工作量太大;)
您可以创建一个代理类,它是 NpgsqlDataReader 的子类/code> 以及重新实现迭代器的位置(扩展 IEnumerable),如果您
.Read()
或询问,它将隐式迭代前最多 2 行>.CountClass
- 然后它会从缓存中给出这 2 个,然后再直接读取其余的。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 (extendsIEnumerable
), 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.