MusiGenesis
MusiGenesis

Reputation: 75296

Does an ADO.NET DataReader read a whole row, or does it only read the columns you "Get"?

If I do something like this:

using (SqlCommand cmd = new SqlCommand("SELECT * FROM TBL"))
{
    using (SqlDataReader reader = cmd.ExecuteReader())
    {
        while (reader.Read())
        {
            string s = reader.GetString(7);
        }
    }
}

does the Read() call read the entire row into memory, or does the GetString(7) call mean that the reader only ever reads the data in column 7?

Upvotes: 2

Views: 1650

Answers (3)

jmoreno
jmoreno

Reputation: 13561

The read operation reads the whole row. The size of the row is determined by your select statement. So, if you have a thousand columns and only want 4, you can do that in your select. If on the otherhand, you want 5 columns if column 1 is Y and 8 columns if it is N, then your out of luck, that can't be done with a single select * from table.

The reason it can't be done is that the call to the database sends back a stream of data (the resultset) as fast as it can, there's no further communication between the two, and even if there was, it would have to be on UNSENT rows as the current row would have already been sent and received. To do what you are talking about would require two way communication on every column, which would kill performance except in truly exceptional circumstances. Doing that even on row basis would typically be inefficient.

Upvotes: 1

MatthewMartin
MatthewMartin

Reputation: 33143

I think you are looking for the ExecuteScalar method of the datareader and you want to specify your columns in your sql command.

Upvotes: 0

lomaxx
lomaxx

Reputation: 115793

it reads the whole row on the read operation.

Upvotes: 4

Related Questions