Click here to Skip to main content
6,630,586 members and growing! (17,442 online)
Email Password   helpLost your password?
Database » Database » ADO.NET     Beginner License: The Code Project Open License (CPOL)

The ADO.NET OleDbDataReader class

By Chris Maunder

Accessing database information using the DataReader class from ADO.NET in C#
C#, Windows, .NET 1.0, .NET 1.1VS.NET2003, Dev
Posted:20 Dec 2000
Updated:22 Aug 2003
Views:196,320
Bookmarked:45 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
52 votes for this article.
Popularity: 7.19 Rating: 4.19 out of 5
1 vote, 6.7%
1

2
1 vote, 6.7%
3
4 votes, 26.7%
4
9 votes, 60.0%
5

Sample Image - ADONET_datareader.gif

Introduction

ADO.NET is the .NET enhanced version of ADO that we all know and love. ADO.NET aims to address some of the deficiencies of traditional ADO and present a model that provides type safety, OOP, and efficiency.

This article will demonstrate the most common task when accessing a database: querying for data and traversing that data from start to finish in order to display the contents (or subset thereof) of a table.

The DataReader class

ADO.NET replaces the concept of data rows with the DataSet object. This essentially provides us with full access to a given database, including all rows, tables and relationships in an object oriented and type-safe manner. It is, however, total overkill for the simple query and traversals that are most often performed on databases.

For this simple case .NET provides us with the DataReader class (OleDbDataReader, OdbcDataReader and SqlDataReader) that is essentially a type safe read only, forward only rowset. The differences between the various flavours of DataReaders is in which data access library they use. SqlDataReader works best with SQL Server, while the others work best with ODBC and OleDB data srouces.

All we need to do is open a connection to a database, send an SQL command, then traverse through the resultant DataReader using the Read command and process the results.

The easiest way to illustrate this is to show you some code. This snippet opens an Access database, reads all the information from a table, then populates a List View control with the data inside.

A few notes on the code:

  • StatusText and fileName are RichTextBox controls declared as
    private System.Windows.Forms.RichTextBox fileName;
    private System.Windows.Forms.RichTextBox StatusText;
  • listView is a list view control declared as
    System.WinForms.ListView listView;
    listView = new System.Windows.Forms.ListView ();

    The list view has been placed in details mode using

    listView.View = System.Windows.Forms.View.Details;

The Code

OleDbConnection Connection = new OleDbConnection ();

try
{
    // Open a connection to the database

    Connection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                                  "Data Source=" + fileName.Text + ";" +
                                  "Persist Security Info=False;";
    Connection.Open();

    // Create an OleDb command, 

    OleDbCommand command = new OleDbCommand();
    command.Connection = Connection;
    command.CommandText = "SELECT * FROM Authors";

    // Execute and return the rows in the data reader object

    OleDbDataReader dataReader;
    dataReader = command.ExecuteReader(CommandBehavior.CloseConnection);

    int nFields = dataReader.FieldCount;

    // Setup the columns in the listview using the fields in the table

    listView.Clear();
    for (int i = 0; i < nFields; i++)
    {
        listView.Columns.Add(dataReader.GetName(i), 100, 
                             HorizontalAlignment.Left);
    }

    // Fill the rows in the listview using the data in the rows

    int nRow = 0;
    while (dataReader.Read())
    {
        // Create an array of subitems for quick insertion

        // The subitems will be all fields in the row except for 

        // the first field

        String [] subitems = new String[nFields];
        for (int i = 0; i < nFields; i++)
        {
            subitems[i] = dataReader[i].ToString();
        }

        // Insert a new item into the listview, and add the subitems at 

        // the same time. The item will be the first field in the row

        ListViewItem item = new ListViewItem(subitems, -1);
        listView.Items.Add(item);

        ++nRow;
    }    
    dataReader.Close();

    // Set the status text

    StatusText.Text = nFields.ToString() + " columns, " + 
          nRow.ToString() + " rows read";
}
catch (Exception ex)
{
    // If an error occured alert the user

    StatusText.Text = "Error: " + ex.Message;
}
finally
{
    // Close the connection if necessary

    if (Connection.State == System.Data.ConnectionState.Open)
        Connection.Close();
}

That's all there is to it. We have closed the database connection but since we are using managed code there is no need (or way) to delete the objects and memory we allocated.

History

23 Aug 2003 - Updated to .NET 1.0/1.1. Previous version was for .NET beta 1.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Chris Maunder


Member
Chris is the Co-founder, Administrator, Architect, Chief Editor and Shameless Hack who wrote and runs The Code Project. He's been programming since 1988 while pretending to be, in various guises, an astrophysicist, mathematician, physicist, hydrologist, geomorphologist, defence intelligence researcher and then, when all that got a bit rough on the nerves, a web developer. He is a Microsoft Visual C++ MVP both globally and for Canada locally.

His programming experience includes C/C++, C#, SQL, MFC, ASP, ASP.NET, and far, far too much FORTRAN. He has worked on PocketPCs, AIX mainframes, Sun workstations, and a CRAY YMP C90 behemoth but finds notebooks take up less desk space.

He dodges, he weaves, and he never gets enough sleep. He is kind to small animals.

Chris was born and bred in Australia but splits his time between Toronto and Melbourne, depending on the weather. For relaxation he is into road cycling, snowboarding, rock climbing, and storm chasing.
Occupation: Founder
Company: The Code Project
Location: Canada Canada

Other popular Database articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 22 of 22 (Total in Forum: 22) (Refresh)FirstPrevNext
GeneralOleDbDataReader Item parameters PinmemberCharuT10:59 1 Nov '06  
GeneralOleDbDataReader with parameters Pinmembersalaikumar5:45 24 Oct '06  
GeneralADO.Net RadioButton.... Pinmembertellek_liberty15:43 31 Jul '04  
GeneralUse for function PinsussAnonymous12:16 30 Mar '04  
Generalhow to know about complete database PinmemberThe Last Action Hero0:25 16 Dec '03  
GeneralDataReader is slooow... PinmemberBraulio Díez5:02 16 Sep '03  
GeneralRe: DataReader is slooow... PinmemberQuentin Pouplard5:24 18 Sep '03  
GeneralRe: DataReader is slooow... PinmemberNavaneethkn0:56 7 Mar '07  
GeneralADO .Net Pinmembercaddsman10:48 5 Sep '03  
GeneralRe: ADO .Net PinmemberKannan Kalyanaraman2:03 6 Sep '03  
GeneralRe: ADO .Net Pinmembercaddsman9:20 8 Sep '03  
GeneralRe: ADO .Net PinmemberKhSergey13:53 6 Sep '03  
Generalreturning multiple "recordsets" PinsussAli Hijazi3:48 1 Jul '03  
GeneralRe: returning multiple "recordsets" PinmemberMike.NET15:41 24 Aug '03  
GeneralADODataReader? PinsupporterPaul Selormey23:01 7 Nov '02  
GeneralRe: ADODataReader? PinmemberVicente Gras7:42 8 Jan '03  
GeneralRe: ADODataReader? PinsupporterPaul Selormey14:12 8 Jan '03  
GeneralMultiple DataReaders PinmemberBrad A. Eaton19:26 16 Jan '02  
GeneralRe: Multiple DataReaders PinmemberChris Maunder20:03 16 Jan '02  
GeneralRe: Multiple DataReaders Pinmemberlizhill0:05 9 Aug '02  
GeneralAdoDataReader and SqlData Reader objects PinmemberRon Teal6:09 11 Jul '01  
GeneralWhat about huge data amounts PinmemberAnonymous7:55 21 Dec '00  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 22 Aug 2003
Editor: Chris Maunder
Copyright 2000 by Chris Maunder
Everything else Copyright © CodeProject, 1999-2009
Web22 | Advertise on the Code Project