繁体   English   中英

SQLDataReader 行数

[英]SQLDataReader Row Count

我试图通过迭代读取器来获取返回的行数。 但是当我运行这段代码时,我总是得到 1? 我在这件事上搞砸了什么吗?

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

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.
 DataTable dt = new DataTable();
 dt.Load(reader);
 int numRows= dt.Rows.Count;

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

dataReader.Cast<object>().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