SQLDataReader行数

26

我试图通过迭代读取器来获取返回的行数,但是每次运行这段代码时都会得到1?我在这里搞错了什么吗?

int count = 0;
if (reader.HasRows)
{
    while (reader.Read())
    {
        count++;
        rep.DataSource = reader;
        rep.DataBind();
    }
}
resultsnolabel.Text += " " + String.Format("{0}", count) + " Results";

4
rep 变量是什么? - bluish
请注意,HasRows 对于我们这些只想区分 1 行或多行 (HasRows==true) 和 0 行 (HasRows == false) 的人非常有用,更多信息请参见HasRows | 类型: System.Boolean 如果 SqlDataReader 包含一个或多个行,则为 true;否则为 false。 - Nate Anderson
4个回答

36
 DataTable dt = new DataTable();
 dt.Load(reader);
 int numRows= dt.Rows.Count;

不错的解决方案,但是.Load方法会消耗Reader(显而易见)。对于那些想要在不消耗Reader的情况下计算记录数量的人(比如在现有代码的某个部分创建一个计数器),我可以节省一些时间。简单来说,这是不可能的。你必须改变代码并使用DataTable。 - undefined

32

SQLDataReaders是只能向前移动的。你基本上正在这样做:

count++;  // initially 1
.DataBind(); //consuming all the records

//next iteration on
.Read()
//we've now come to end of resultset, thanks to the DataBind()
//count is still 1 
你可以这样做:
if (reader.HasRows)
{
    rep.DataSource = reader;
    rep.DataBind();
}
int count = rep.Items.Count; //somehow count the num rows/items `rep` has.

15
rep 是什么类型的变量? - Giancarlo Benítez
1
我认为rep是一个GridView。 - Tony Rush

13

这将获取行数,但会使数据读取器停留在末尾。

dataReader.Cast<object>().Count();

-9
也许你可以尝试这个:但请注意 - 这会提取列数,而不是行数。
 using (SqlDataReader reader = command.ExecuteReader())
 {
     while (reader.Read())
     {
         int count = reader.VisibleFieldCount;
         Console.WriteLine(count);
     }
 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接