Robert
Robert

Reputation: 13

Why use empty loop for datareader?

I'm making a n-tier web application, and created a method to add data to a specific database. My question is when making a connection to the database and executing the query, why is there a loop for the DataReader object with nothing in it. Here is my method:

while (myReader.Read())
{

}

Upvotes: 0

Views: 75

Answers (2)

Ali Bahrami
Ali Bahrami

Reputation: 6073

DataReader doesn't fetch data at once, it only starts reading a record when you call the Read method. Actually, the read method advances the SqlDataReader to the next record so it returns true if there are more rows; otherwise false.

while(dataReader.Read()) // true if there are more rows; otherwise false.
{
    // code to run
}

You can read about it here in MSDN.

Upvotes: 3

SmartestVEGA
SmartestVEGA

Reputation: 8899

myReader.Read() true if there are more rows; otherwise false.

Refer : https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqldatareader.read?view=netframework-4.8

Upvotes: 0

Related Questions