【问题标题】:SQLDataReader Row CountSQLDataReader 行数
【发布时间】:2011-07-27 01:10:09
【问题描述】:

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

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

【问题讨论】:

  • 什么是rep变量?
  • 请注意HasRows 对于我们这些只想区分 1 行或多行 (HasRows==true) 和 0 零行 (HasRows == false) 的人很有用,more here HasRows | Type: System.Boolean true if the SqlDataReader contains one or more rows; otherwise false.

标签: c# sql sqldatareader


【解决方案1】:

SQLDataReader 是只进的。您实际上是在这样做:

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.

【讨论】:

  • rep是什么类型的变量?
  • 我认为 rep 是一个 GridView
【解决方案2】:
 DataTable dt = new DataTable();
 dt.Load(reader);
 int numRows= dt.Rows.Count;

【讨论】:

  • 帮了很多忙...+1
  • 这太棒了
【解决方案3】:

这将为您提供行数,但会将数据读取器留在最后。

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

【讨论】:

    【解决方案4】:

    也许你可以试试这个:虽然请注意 - 这会拉动列数,而不是行数

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

    【讨论】: