简体   繁体   English

SQLDataReader 行数

[英]SQLDataReader Row Count

I am trying to get the number of rows that were returned by iterating the reader.我试图通过迭代读取器来获取返回的行数。 But I always get 1 when I run this code?但是当我运行这段代码时,我总是得到 1? Did I screw up something in this?我在这件事上搞砸了什么吗?

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

SQLDataReaders are forward-only. SQLDataReaders 是只进的。 You're essentially doing this:你基本上是这样做的:

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 

You could do this instead:你可以这样做:

if (reader.HasRows)
{
    rep.DataSource = reader;
    rep.DataBind();
}
int count = rep.Items.Count; //somehow count the num rows/items `rep` has.
 DataTable dt = new DataTable();
 dt.Load(reader);
 int numRows= dt.Rows.Count;

这将为您提供行数,但最终会离开数据读取器。

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

Maybe you can try this: though please note - This pulls the column count, not the row count也许你可以试试这个:不过请注意 - 这会拉出列数,而不是行数

 using (SqlDataReader reader = command.ExecuteReader())
 {
     while (reader.Read())
     {
         int count = reader.VisibleFieldCount;
         Console.WriteLine(count);
     }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM