TheChaseMan's Frenetic SoapBox

Always looking for better ways to do things...

Create Database Agnostic Code with ADO.NET 2.0

There have been several times where I've needed to create an architecture that is database agnostic. For example, a solution that could use either SQL Server or an Oracle backend. With .NET 1.x, there are things you can do such as leverage common base classes or interfaces similar to the .NET Petshop example. This is implemented by using the factory design pattern, and a "plug-in" allowing you to make a simple configuration setting change to switch database types on the fly or when rolling out the solution. Another way I've achieved this is to use LLBLGen Pro's adapter configuration.

Fortunately, you can achieve this design goal very easily with the .NET Framework 2.0 using DB Provider Factories. Below is an example of how you can do this. First is the App.config settings followed by code...

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

  <connectionStrings>

    <add name="Northwind" providerName="System.Data.SqlClient"

      connectionString="Data Source=.;Initial Catalog=Northwind;

                       integrated security=SSPI" />

  </connectionStrings>

</configuration>

class Program

{

    static void Main(string[] args)

    {

        //from the System.Configuration assembly

        ConnectionStringSettings cnstrSettings = ConfigurationManager.ConnectionStrings["Northwind"];

 

        DbProviderFactory factory = DbProviderFactories.GetFactory(cnstrSettings.ProviderName);

 

        using(DbConnection connection = factory.CreateConnection())

        using(DbCommand command = factory.CreateCommand())

        {

            connection.ConnectionString = cnstrSettings.ConnectionString;

            connection.Open();

            command.Connection = connection;

            command.CommandText = "SELECT * FROM Customers";

            using (DbDataReader reader = command.ExecuteReader())

            {

                int customerIdOrdinal = reader.GetOrdinal("CustomerID");

                int companyNameOrdinal = reader.GetOrdinal("CompanyName");

                while (reader.Read())

                {

                    Console.WriteLine(String.Format("CustomerID = {0}, Company Name = {1}",

                        reader.GetString(customerIdOrdinal),

                        reader.GetString(companyNameOrdinal)));

                }

            }

        }

    }
}


Digg!

posted on Saturday, November 05, 2005 3:45 PM

Feedback

No comments posted yet.