Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does fetching data from SQL Server to SqlDataReader work?

When I call this code:

using (var connection = new SqlConnection(connectionString))
{
    var command = new SqlCommand("SELECT * FROM Table", connection);
    connection.Open();
    using (var reader = command.ExecuteReader())
    {
        while(reader.Read())
        {
            // Do something here
        }
    }
}

what happens internally? How does this work on a network level? Will it make a new round trip to database for each call to Read or is there any batch read implemented internally?

I'm asking because I just read that ODP.NET provides FetchSize property in both OracleCommand and OracleDataReader which I understand as definition of how many records should be preloaded by single round trip to the database. I wonder if SQL Server works in similar fashion and if there is some similar behavior which can be configured somewhere. I didn't find any such configuration in SqlCommand, SqlDataReader or CommandBehavior.

like image 938
Ladislav Mrnka Avatar asked May 17 '11 15:05

Ladislav Mrnka


People also ask

What does SqlDataReader return?

As explained earlier, the SqlDataReader returns data via a sequential stream. To read this data, you must pull data from a table row-by-row Once a row has been read, the previous row is no longer available.

How do I get data from ExecuteReader?

To retrieve data using a DataReader, create an instance of the Command object, and then create a DataReader by calling Command. ExecuteReader to retrieve rows from a data source.

What is SqlDataReader explain it with relevant example?

The SqlDataReader is used to read a row of record at a time which is got using SqlCommand. It is read only, which means we can only read the record; it can not be edited. And also it is forward only, which means you can not go back to a previous row (record).

How does SQL reader work?

It reads them as it has time in the background. By the time you had gone to SQL Server and closed the connection, all the data had transferred over in the background. What happens when you execute the reader, is that it calls SQL Server, and tells it to start sending results.


1 Answers

the data is streamed from sql server to the client in the packets of the size in SqlConnection.PacketSize property. If your client can't read results fast enough the buffer on the network card gets filled up, the protocol detects this and stops receiving which in turn makes sql server's network card send buffer full and it stops sending any and all data. if you want to go down to the protocl level then check out TDS protcol.

like image 68
Mladen Prajdic Avatar answered Sep 20 '22 09:09

Mladen Prajdic