[英]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.