C#. ADO .NET. Class DbDataReader

Connected mode. Class DbDataReader


Search other resources:


Contents


1. Purpose of DbDataReader class

The DbDataReader class provides a data reader for connected mode. An object of the DbDataReader class is designed to read records (rows) from a database table. Reading is carried out at the moment of opening a connection to the database. The class implements a one-way sequential reading. Compared to the DataSet object, this class provides better performance when accessing data by reducing overhead.

The DataReader object is not suitable for handling data between different layers of the application because the connection remains open when the DataReader object is connected.

 

2. Methods and properties of class DbDataReader

When reading data, the DataReader class uses a number of options and methods.

The properties of the DataReader class are listed below.

Property Data type Explanation
Depth Int32 Determines the nesting level of the current row. Read-only property
FieldCount Int32 The number of fields in the DataReader object. Read-only
HasRows Boolean Indicates whether the DbCommand query returned records. Read-only
IsClosed Boolean Indicates whether the DataReader is closed. Read only
Item Object Returns the contents of each field in the current record. Read only
RecordAffected Int32 Indicates the number of records involved by executed queries. This property is read-only

The methods of the DbDataReader class are as follows.

Method Explanation
Close Closes the DbDataReader object

Get<DataType>

 

GetString,

GetInt32,

GetDouble,

Returns the contents of the specified field of the current row, based on the index number of this field. The method sets the type of the specified field

string strStudentName;
SqlDataReader rdr;

...

strStudentName = rdr.GetString(intStudentNameIndex);

or

strStudentName = (string)rdr.GetValue(intStudentNameIndex);
GetBytes Returns an array of bytes from the specified field of the current record
GetChars Returns an array of characters from the specified field of the current record
GetData Returns a new DbDataReader object based on the given field
GetDataTypeName Returns the name of the data type of the field based on the ordinal number of the field in the record
GetFieldType Returns the data type of the field by the ordinal number of the field
GetName Returns the field name by its ordinal number
GetOrdinal Returns the ordinal number of a field based on its name
GetValue Returns the value of a field by its ordinal as a .NET data type
GetValues Accepts an array through which an object of type DbDataReader returns the contents of the current column. Returns a 32-bit integer when called, which corresponds to the number of entries in the array

SqlDataReader rdr = command.ExecuteReader();
object[] aData = new object[rdr.FileCount];
while (rdr.Read())
{
  rdr.GetValues(aData);
  Console.WriteLine(aData[0].ToString());
}
IsDbNull Indicates whether a field contains a Null value
NextResult Used in cases where there is a batch query that returns multiple result sets. The method implements the transition to the next result set
Read Moves to the next record

An object of type DataReader can receive data from various sources, including an SQL query contained in an object of type Command (DbCommand, SqlCommand, OledbCommand, OdbcCommand). After receiving the data, it is possible to cancel the reading of the data using the Cancel() method.

 

3. An example of getting data

The example demonstrates reading data from a database named Database4. A table is created in the database named Table1, which has a data structure consisting of 3 columns.

The columns of the table have the following purpose

  • Id – unique identifier, autoincrement field;
  • Name – last name and first name of the student;
  • Address – the student’s address.

The table rows are filled with values as shown in the table.

Id Name Address
1 Student1 Address-01
2 Student2 Address-02
3 Student3 Address-03

To display all the rows and columns of table in the ListBox component for Windows Forms application, you can use, for example, the following code.

private void GetDataFromDataBase()
{
  // Read data from database
  // 1. Query string
  string queryStr = "SELECT * FROM [dbo].[Table1]";

  // 2. Connection string
  string connStr = @"Data Source=(localdb)\ProjectModels;" +
    "Initial Catalog=Database4;Integrated Security=True;";

  // 3. Get data
  using (SqlConnection connection =
    new SqlConnection(connStr))
  {
    try
    {
      // Create SQL-command
      DbCommand command = connection.CreateCommand();
      command.CommandText = queryStr;
      command.CommandType = CommandType.Text;

      // Open the connection
      connection.Open();

      // Get data - class DbDataReader
      DbDataReader dataReader = command.ExecuteReader();

      // Display data to listBox1
      listBox1.Items.Clear();
      while (dataReader.Read())
      {
        listBox1.Items.Add(dataReader[0].ToString() + " - " +
        dataReader[1].ToString());
      }
    }
    catch (Exception e)
    {
      MessageBox.Show(e.Message);
    }
    finally
    {
      // Close the connection
      connection.Close();
    }
  }
}

 

4. Method GetName(). Field FieldCount. Get the name of a column (field) in a table

To get the field name from a database table, use the GetName() method. Accordingly, the number of table fields is determined using the FieldCount property, which is read-only.

For example, for the following table

Id Name Address

calling the method from a DataReader object named dataReader

dataReader.GetName(0);

will return “Id” string.

And the call

dataReader.GetName(2);

will return the “Address” string.

The following example is a code snippet that displays the names of all fields in a table named Table1 in Database4. The fields are displayed in the ListBox component. The example is implemented for Windows Forms application.

private void button7_Click(object sender, EventArgs e)
{
  // Get a list of field names based on the result of an SQL query and add them to the ListBox
  // 1. Connection string
  string connStr = @"Data Source=(localdb)\ProjectModels;" +
    "Initial Catalog=Database4;Integrated Security=True;";

  // 2. The text of SQL-query
  string strSQL = "SELECT * FROM [dbo].[Table1]";

  // 3. Connect to the database and get the data
  using (SqlConnection connection =
    new SqlConnection(connStr))
  {
    try
    {
      // Create the SQL-command
      DbCommand command = connection.CreateCommand();
      command.CommandText = strSQL;
      command.CommandType = CommandType.Text;

      // Open the connection
      connection.Open();

      // Get data - class DbDataReader
      DbDataReader dataReader = command.ExecuteReader();

      // Display the names of the table columns in listBox1
      listBox1.Items.Clear();

      // FieldCount - the number of columns in the table from which data is being read
      for (int i = 0; i < dataReader.FieldCount; i++) 
      {
        // Get the field name
        string s = dataReader.GetName(i);

        // Display the field name in the ListBox
        listBox1.Items.Add(s);
      }

      // Close the dataReader object
      dataReader.Close();
    }
    catch (Exception ex)
    {
      MessageBox.Show(ex.Message);
    }
    finally
    {
      // Close the connection
      connection.Close();
    }
  }
}

 

5. Method GetFieldType(). Get the data type name of a field (column) based on its serial number (0, 1, 2, …) as a .NET type

The GetFieldType() method returns an instance of type Type with data about the type of the field filled in. The general form of a method declaration is as follows

Type DbDataReader.GetFieldType(int ordinal);

here

  • ordinal – ordinal number of the column (field) in the table containing the rows represented by the DataReader object.

The following example shows how to read the data types of all fields in a given table.

private void button8_Click(object sender, EventArgs e)
{
  // Get the name of the field's data type
  // 1. Connection string
  string connStr = @"Data Source=(localdb)\ProjectModels;" +
    "Initial Catalog=Database4;Integrated Security=True;";

  // 2. The SQL-query
  string strSQL = "SELECT * FROM [dbo].[Table1]";

  // 3. Connect to the database and get the data
  using (SqlConnection connection =
    new SqlConnection(connStr))
  {
    try
    {
      // Create the SQL-command
      DbCommand command = connection.CreateCommand();
      command.CommandText = strSQL;
      command.CommandType = CommandType.Text;

      // Open the connection
      connection.Open();

      // Get data - class DbDataReader
      DbDataReader dataReader = command.ExecuteReader();

      // Display data type names of table columns in listBox1
      listBox1.Items.Clear();

      // FieldCount - the number of columns in the table from which data is being read
      for (int i = 0; i < dataReader.FieldCount; i++) // iterate over all fields
      {
        // Get the field name
        string s = dataReader.GetFieldType(i).Name;

        // Display the field name in the ListBox
        listBox1.Items.Add(s);
      }

      // Close the dataReader object
      dataReader.Close();
    }
    catch (Exception ex)
    {
      MessageBox.Show(ex.Message);
    }
    finally
    {
      // Close the connection
      connection.Close();
    }
  }
}

For the table presented in p.p. 3-4 the result of adding fields to the ListBox are rows

Int32
String
String

 

6. Method GetDataTypeName(). Get the name of the data type in the database based on the serial number (0, 1, 2, …)

The general form of the declaration of the GetDataTypeName() method is:

string GetDataTypeName(int ordinal);

A fragment that reads a list of data types from the dataReader object of type DbDataReader and writes them to the ListBox component (application of type Windows Forms).

...

// Display the datatype names of the table columns in listBox1
listBox1.Items.Clear();

// FieldCount - the number of columns in the table from which data is being read
for (int i = 0; i < dataReader.FieldCount; i++) // iterate over all fields
{
  // Get the field name
  string s = dataReader.GetDataTypeName(i);
  listBox1.Items.Add(s);
}

...

For the data table from points 3, 4, the result of the program will be

int
nchar
nchar

 


Related topics