C# Retrieving correct DbConnection object by connection string

37,251

Solution 1

DbConnection GetConnection(string connStr)
{
    string providerName = null;
    var    csb = new DbConnectionStringBuilder { ConnectionString = connStr };
                                                        
    if (csb.ContainsKey("provider")) 
    {
        providerName = csb["provider"].ToString();
    }          
    else
    {
        var css = ConfigurationManager
            .ConnectionStrings
            .Cast<ConnectionStringSettings>()
            .FirstOrDefault(x => x.ConnectionString == connStr);
        if (css != null) providerName = css.ProviderName;
    }
           
    if (providerName != null) 
    {
        var providerExists = DbProviderFactories
            .GetFactoryClasses()
            .Rows.Cast<DataRow>()
            .Any(r => r[2].Equals(providerName));
        if (providerExists) 
        {
            var factory = DbProviderFactories.GetFactory(providerName);
            var dbConnection = factory.CreateConnection();
                
            dbConnection.ConnectionString = connStr;
            return dbConnection;
        }
    }
           
    return null;
}

Solution 2

if you're using framework 2.0 or above, and you can get them to pass in a second string with the driver class, you can use the dbProviderFactory class to load the driver for you.

DbProviderFactory dbProviderFactory = DbProviderFactories.GetFactory(myDriverClass);
DbConnection dbConnection = dbProviderFactory.CreateConnection();
dbConnection.ConnectionString = myConnectionString;

Here's an MSDN link to the Factory class: http://msdn.microsoft.com/en-us/library/wda6c36e.aspx

Solution 3

You should be able to parse out the Provider section and pass it into DbProviderFactories.GetFactory which will return a OdbcFactory, OleDbFactory or SqlClientFactory and let you then perform CreateConnection etc.

I'm not sure how this would work with Oracle unless they provide an OracleDbFactory.

Solution 4

Most connection strings (at least in .NET 2.0) also have a providerName property that goes with them. So a SQL connection string will have a provider Name like:

providerName="System.Data.SqlClient"

So your method would need to accept both the connection string and the provider name and then you could use the DbProviderFactory as mentioned by damieng.

Share:
37,251

Related videos on Youtube

johnc
Author by

johnc

A former Java, Cold Fusion, VB, Infopump, OpenROAD, asp, jsp, php, javascript, actionscript, C, C++ developer. I now pretty much stick to C#, nodejs and Java for Android, but explore off the beaten track when required.

Updated on July 09, 2022

Comments

  • johnc
    johnc almost 2 years

    I have a connection string being passed to a function, and I need to create a DbConnection based object (i.e. SQLConnection, OracleConnection, OLEDbConnection etc) based on this string.

    Is there any inbuilt functionality to do this, or any 3rd party libraries to assist. We are not necessarily building this connection string, so we cannot rely on a format the string is written in to determine its type, and I would prefer not to have to code up all combinations and permutations of possible connection strings

  • Philipp Munin
    Philipp Munin over 10 years
    I also don't think it's gonna work for OleDb connection strings like: Provider=Microsoft.ACE.OLEDB.12.0;Data Source=9cb8a4c4-9661-4c10-a21c-fb4a85ce2471.xlsx;Mode=ReadWr‌​ite;Extended Properties="Excel 12.0 Xml;HDR=YES;IMEX=0;"
  • Mark Cidade
    Mark Cidade over 10 years
    No, it will only return an OLEDB connection if the provider is specified as "System.Data.OleDb" or if the connection string is specified in the configuration.
  • Mr. Boy
    Mr. Boy almost 8 years
    I find this really surprising, that you can't make your code DB-independent without this kind of hassle.