Tuesday 13 July, 2010

How do I write common code for different dot net framework data providers?


The System.Data namespace contains the interfaces implemented by different dot net framework data providers, such as:
  • IDbConnection implemented by SqlConnection, OracleConnection, OleDbConnection, OdbcConnection classes represents a connection with the database server
  • IDbCommand implemented by SqlCommand, OracleCommand, OleDbCommand, OdbcCommand classes represents an SQL command passed to the database server
  • IDbDataAdapter implemented by SqlDataAdapter, OracleDataAdapter, OleDbDataAdapter, OdbcDataAdapter classes represents a data adapter used to fill the data set in the disconnected environment of the ADO.Net
  • IDataReader implemented by SqlDataReader, OracleDataReader, OleDbDataReader, OdbcDataReader classes represents a data reader used to read records from the database server, analogous to read only, forward only cursor
  • IDbTransaction implemented by SqlTransaction, OracleTransaction, OleDbTransaction, OdbcTransaction classes represents a transaction established with the database server
We strongly recommend the readers to use the references of these interface type to perform the database operations wherever possible. Using these, you can write a code that is data provider independent. Consider a data access module which is supplied the database connection and which performs the database operations using this connection. This module does not know which data provider the connection belongs and uses the interface approach. Following code demonstrate this data access module

C# Version
internal class DataAccessModule {  private IDbConnection conn;  private IDbCommand cmd;  private const string GetValueCmdText ="SELECT value FROM MyTable WHERE name = '";     public DataAccessModule(IDbConnection conn)  {   this.conn = conn;   cmd = conn.CreateCommand();   conn.Open();  }  public string GetValue(string name)  {            cmd.CommandText = GetValueCmdText + name + "'";   IDataReader reader = cmd.ExecuteReader();   if(reader.Read())   {    return reader["value"].ToString();   }   else   {    return null;   }  }  // more functions... } 


VB.Net Version
Friend Class DataAccessModule     Private conn As IDbConnection     Private cmd As IDbCommand     Private Const GetValueCmdText As String ="SELECT value FROM MyTable WHERE name = '"     Public Sub New(ByVal conn As IDbConnection)         Me.conn = conn         cmd = conn.CreateCommand()         conn.Open()     End Sub     Public Function GetValue(ByVal name As String) As String         cmd.CommandText = GetValueCmdText + name + "'"         Dim reader As IDataReader = cmd.ExecuteReader()         If (reader.Read()) Then             Return reader("value").ToString()         Else             Return Nothing         End If     End Function     ' More Functions.... End Class 

No comments:

Post a Comment