none
How does SqlDataReader.Read() work internally? RRS feed

  • Question

  • In classic ADO .NET, there is a very simple command for reading rows from a table. It is called SqlDataReader.Read():

    // Initialization logic
    ...
    using (SqlDataReader reader = cmd.ExecuteReader())
    
    while (reader.Read())
    {
        // Row fetching logic
    }

    I understand that reader.Read() returns a Boolean and based on its value, the cursor will continue reading the next record. 

    What I don't understand precisely is how it actually advances the SqlDataReader to the next record, as the documentation indicates.

    I have inspected the internal code of .Read(), only to find a very complicated set of logic which has a flow that I don't immediately understand - especially the submethod TryReadInternal(). 

    A lot of things are going on in this internal logic and I just want to get a clear idea of how it essentially allows the SqlDataReader to read data from the current record and move on to the next record. After all, it's just returning a Boolean (or is it?), or is it doing more for the SqlDataReader than just returning a Boolean? Does it populate the SqlDataReader with a row and then return a boolean? What exactly is going on here? How is .Read() allowing the SqlDataReader to get row data and a cursor position?

    I'm asking this because it seems that without the .Read() command, I can't read data from the table, so it must be doing something special behind the scenes.

    Thanks.

    Saturday, April 29, 2017 12:35 PM

Answers

  • Does it populate the SqlDataReader with a row and then return a boolean? 

    In summary, yes.  The Read method simply advances the client cursor to the next record and returns true when data are available and false when the end of data is reached.  One can retrieve values from the record only when Read returns true because there is no current record when false is returned.

    The ExecuteReader method of SqlCommand sends a batch of one or more SQL statements to the SQL Server database engine for execution and returns a SqlDataReader instance back to the application to retrieve the results.  Query results are returned by SQL Server as a stream of data over the TDS protocol, which the SqlDataReader buffers, parses, and exposes the data via its methods and properties. 


    Dan Guzman, Data Platform MVP, http://www.dbdelta.com

    • Marked as answer by CodeOfLogic Tuesday, May 2, 2017 4:53 PM
    Saturday, April 29, 2017 4:10 PM