• Home
  • About
Blue Orange Green Pink Purple

Using generic database providers with C#

Posted in Uncategorized. on Tuesday, November 17th, 2009 by Chris Hulbert
Nov 17

This snippet of code shows how to use the generic System.Data.Common types to connect to any database, using a string to define which database provider you want to use. The magic happens with the 'Activator.CreateInstance' below, where C# has the ability to create a class from a string.

This example below is Oracle centric, but to change it to work with Sql server you'd simply change the connection string and the provider, which are both strings hence easily configurable in a text file for your application!

using System;
using System.Data.Common;

namespace OdpTest
{
  class Program
  {
    static void Main(string[] args)
    {
      string connectionString =
        "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)" +
        "(HOST=MYHOST)(PORT=1527))(CONNECT_DATA=(SID=MYSERVICE)));" +
        "User Id=MYUSER;Password=MYPASS;";
      string provider =
        "Oracle.DataAccess.Client.OracleConnection, Oracle.DataAccess";

      using (DbConnection conn = (DbConnection)Activator.
        CreateInstance(Type.GetType(provider), connectionString))
      {
        conn.Open();
        string sql =
          "select distinct owner from sys.all_objects order by owner";
        using (DbCommand comm = conn.CreateCommand())
        {
          comm.CommandText = sql;
          using (DbDataReader rdr = comm.ExecuteReader())
          {
            while (rdr.Read())
            {
              string owner = rdr.GetString(0);
              Console.WriteLine("{0}", owner);
            }
          }
        }
      }
    }
  }
}

Leave a Reply

Chris' Babble

  • About
    Hi, i'm Chris Hulbert, a software guy from Sydney Australia.
  • Categories
    • code
    • Portfolio
    • Uncategorized
  • Recent Articles
    • How to implement DES and Triple DES from scratch
    • How to use Cookies in Struts 2 with ServletRequest and ServletResponse
    • How to use sessions with Struts 2
    • Using Quartz Scheduler in a Java web app (servlet)
    • Javascript date picker that Doesn't Suck!(tm)
    • Using Oracle XE with Hibernate


  • Home
  • About

© Copyright Chris' Babble. All rights reserved.
Designed by FTL Wordpress Themes brought to you by Smashing Magazine

Back to Top