Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a .NET SqlDataReader object use a database cursor, or the whole result set is loaded into RAM?

Here is a sample code of using the SqlDataReader:

// Working with SQLServer and C#
// Retrieve all rows
cmd.CommandText = "SELECT some_field FROM data";

using (var reader = cmd.ExecuteReader())
{
    while (reader.Read())
    {
        Console.WriteLine(reader.GetString(0));
    }
}

EDIT :

I mean I want to understand whether there is the same mechanism when retrieving data from database in a while-loop (in case of SqlDataReader) as it does when working with the SQLite.

// working with SQLite and Java
if (cursor.moveToFirst()) {
   do {
      String data = cursor.getString(cursor.getColumnIndex("data"));
      // do what ever you want here
   } while(cursor.moveToNext());
}
cursor.close();
like image 263
AlexMelw Avatar asked Apr 17 '17 13:04

AlexMelw


People also ask

How to retrieve data from database in c# using SqlDataReader?

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 the use of SqlDataReader in C#?

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 DataReader work?

The data reader reads a record at a time, but it reads it from the underlying database driver. The database driver reads data from the database in blocks, typically using a buffer that is 8 kilobytes.


1 Answers

No, there's no cursor on the server side unless your command is calling a stored procedure that uses a cursor. The server is returning a plain-vanilla SQL result set, one row at a time, when you use a SqlDataReader. Obviously, the data's got to be somewhere before you can read it, and that place would be buffer(s) that SQL Server and the drivers manage.

If you were to push this into using something like a Dataset, then all the rows would be in RAM at once.

like image 117
Xavier J Avatar answered Sep 23 '22 06:09

Xavier J