IDataReader - 获取总行数的任何方法?

时间:2011-07-18 14:09:29

标签: c# count rows datareader

在使用reader.Read();迭代行之前,有没有办法获取SQL查询(来自IDataReader)返回的总行数?

5 个答案:

答案 0 :(得分:10)

没有

IDataReader是结果集的简单前向视图;它无法计算。

答案 1 :(得分:5)

不,datareader不会先返回计数。但是,如果确实需要这样做,请使用两个返回多个结果集的查询。

例如在SQL Server中:

sql = "SELECT COUNT(1) FROM A; SELECT * FROM A;"

迭代结果集。在第二个结果集上使用IDataReader

如果使用适当的索引,数据库服务器应该能够非常快速地执行此操作。

答案 2 :(得分:4)

过了发布的日期,但是有一种方法,对我来说有用了一段时间才能获得,因为我对谷歌搜索的措辞很糟糕。

dbCommand.Connection.Open();
//dbReader = dbCommand.ExecuteReader();  I left this here to show not to do the read

searchCount = dbCommand.ExecuteScalar(); // this line returns the value count
                                         // from my tests on my reader it works perfectly

答案 3 :(得分:0)

仅在读取DataReader时计算的行数 但是我没弄明白,为什么你想在阅读之前知道行数。

答案 4 :(得分:0)

也许不是一个好主意,但是我在while循环中使用了变量来计数。这段代码对我来说很好:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int a, b;
    scanf("%d", &a);

    if(a<0, a>1000)
    {
        printf("Number must be in the range of 0~1000"); //set the range of the input number
        exit(0);
    }   

    for(b =1; b<=a; ++b)
    {
        if(a%b==0)
        printf("%d ", b); //calculate the divisors
    }

    // the next part of the code which I can't figure out

    return 0;
}