Click here to Skip to main content
15,879,535 members
Articles / Programming Languages / C#
Article

Typed SQLDataReader

Rate me:
Please Sign up or sign in to vote.
4.89/5 (13 votes)
16 Aug 20042 min read 173.9K   946   37   19
This article would describe how to read column values based on column names, using SQLDataReader.

Introduction

SQLDataReader provides a way to access the records in forward direction from the database. A typed SQLDataReader would provide an interface to read the column data using friendly column names.

SQLDataReader

.NET has provided a new different ways to access data based on various scenarios. SQLDataReader is one of the fastest ways of accessing a SQL Server database as it reads data in one direction- forward read only.

Limitation

To read column value from SQLDataReader object, one needs to call the function with column ordinal as the input parameter. This is tedious as it requires changes in the column parameter again on any changes in the SQL column sequence.

One could also read column values based on column names, provided user explicitly casts the property to proper data type.

Solution

To counter these issues, I created a new class that would take input as column names and returns the value with appropriate data type same like using column ordinals. This class would also provide functionality to handle null values.

The class SmartDataReader has the same function names but different signatures to access the column values as that of SQLDataReader. SmartDataReader class uses the SQLDataReader object that is initialized in the constructor of this class. The rest of the call handling is done by calling the appropriate method of this object inside the class.

Example:

Different ways to access int column(“EmpID”):

Using SQLDataReader (Column Ordinal)Reader.GetInt32(1)
Using SQLDataReader (Column Name)Convert.ToInt32(Reader[“EmpID”])
Using SmartSQLDataReaderSmartReader.GetInt32(“EmpID”)

As you could see, to use the SQLDataReader with column names, we need to explicitly perform the proper casting. This is not the case with SmartDataReader which works same way as using column ordinals.

Sample:

C#
public sealed class SmartDataReader
{
private DateTime defaultDate;
public SmartDataReader(SqlDataReader reader)
{
    this.defaultDate = DateTime.MinValue;
    this.reader = reader;
}
 
public int GetInt32(String column)
{
    int data = (reader.IsDBNull(reader.GetOrdinal(column))) 
                            ? (int)0 : (int)reader[column];
    return data;
}
 
public short GetInt16(String column)
{
    short data = (reader.IsDBNull(reader.GetOrdinal(column))) 
                          ? (short)0 : (short)reader[column];
    return data;
}
 
public float GetFloat(String column)
{
    float data = (reader.IsDBNull(reader.GetOrdinal(column))) 
                ? 0 : float.Parse(reader[column].ToString());
    return data;
}
 
public bool GetBoolean(String column)
{
    bool data = (reader.IsDBNull(reader.GetOrdinal(column))) 
                             ? false : (bool)reader[column];
    return data;
}
 
public String GetString(String column)
{
    String data = (reader.IsDBNull(reader.GetOrdinal(column))) 
                           ? null : reader[column].ToString();
    return data;
}
 
public DateTime GetDateTime(String column)
{
   DateTime data = (reader.IsDBNull(reader.GetOrdinal(column))) 
                      ? defaultDate : (DateTime)reader[column];
   return data;
}
 
public bool Read()
{
   return this.reader.Read();
}
private SqlDataReader reader;
}
/// <summary>
/// Read from database using SmartDataReader
/// </summary>
public void ReadData()
{
    SqlConnection connection = new 
        SqlConnection("Initial Catalog=Northwind;Data Source=Test;" + 
        "Integrated Security=SSPI;");
    SqlDataReader reader = null;
    try
    {
        connection.Open();
        string sql = "SELECT EmployeeID, FirstName, BirthDate FROM Employees";
        SqlCommand command = new SqlCommand();
        command.CommandText = sql;
        command.Connection = connection;
        reader = command.ExecuteReader();
        SmartDataReader smartReader = new SmartDataReader(reader);
        while(smartReader.Read())
        {
            int idSmart = smartReader.GetInt32("EmployeeID"); 
            string nameSmart = smartReader.GetString("FirstName"); 
            DateTime dateSmart = smartReader.GetDateTime("BirthDate");
        }
    }
    catch(SqlException e)
    {                   
        Console.WriteLine(String.Format("An exception occurred" + 
                " : {0}. Please contact your system administrator.", 
                e.Message));
    }
    finally
    {
        if(reader != null) reader.Close();
        if(connection != null) connection.Close();
    }
}

This sample opens a database connection to the SQL Server database. A SQLDataReader object is created based on the SQL query, and this object is passed to the constructor of SmartDataReader class object. Once SmartDataReader object is set, all table values are accessed by using SmartDataReader object.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Architect
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralRock On! Pin
dwatkins@dirq.net5-Jun-07 12:04
dwatkins@dirq.net5-Jun-07 12:04 
GeneralVery Useful Pin
pfeds19-May-07 3:59
pfeds19-May-07 3:59 
GeneralMissed Line Pin
mohamedrady3-Apr-06 15:01
mohamedrady3-Apr-06 15:01 
GeneralSweet... Pin
Jolio18-Jan-05 10:25
Jolio18-Jan-05 10:25 
GeneralAccess database from C#.Net via ODBC Pin
Will L Pittenger12-Oct-04 22:48
Will L Pittenger12-Oct-04 22:48 
GeneralRe: Access database from C#.Net via ODBC Pin
S Sansanwal21-Oct-04 12:51
S Sansanwal21-Oct-04 12:51 
GeneralGood Pin
Raghavendra Sagar Gaur23-Aug-04 23:47
Raghavendra Sagar Gaur23-Aug-04 23:47 
GeneralNice Pin
David Kemp18-Aug-04 0:57
David Kemp18-Aug-04 0:57 
GeneralRe: Nice Pin
bondsbw5-May-06 11:36
bondsbw5-May-06 11:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.