简体   繁体   中英

SqlDataAdapter and SqlDataReader

I have a stored procedure which returns a certain number of rows.

Case 1: When I use SqlDataAdapter

SqlDataAdapter sdAdapter = new SqlDataAdapter();
ds = new DataSet();
sdAdapter.SelectCommand = myCommand;
sdAdapter.Fill(ds);
int recordCount = ds.Tables[0].Rows.Count;

Case 2: When I use SqlDataReader

SqlDataReader reader = myCommand.ExecuteReader();
if (reader.HasRows)
{
   while (reader.Read())
    {
     recordCount++;
    }
 }

In Case 1, the recordCount is 15 which is correct.

In Case 2, for some reason, reader.HasRows is returning false.

Am I doing anything wrong in terms of syntax? I am confident that myCommand has been built properly since I do get the count in Case 1.

Any help would be really appreciated.

Thank you

1.A DataReader works in a connected environment, whereas DataSet works in a disconnected environment. 2.A DataSet represents an in-memory cache of data consisting of any number of inter related DataTable objects. A DataTable object represents a tabular block of in-memory data.

more detail go to sqldataadapter or sqldatareader

if (reader.HasRows) is redundant. When you say while (reader.Read()) , it will only loop if there are any rows. Also, this link will explain that HasRows requires a scrollable cursor. Read about the cursors here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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