Question

I want to be able to get data from multiple data sources with the same code. Inside my program I get several connection string for different data sources (propably ODBC, OLE DB and SQL).

Now I don't want to write seperate code for every data connection. I can tell which classes the connection strings are meant to be used with (e.g. OleDbConnection, SqlConnection, OdbcConnection). Apparently all of them are inheritors of the class DbConnection. I wonder if i can use that to write one class which accesses them all?

Was it helpful?

Solution

Yes, you can do this in .NET 2.x or later using a DbProviderFactory:

ConnectionStringSettings c = ConfigurationManager.ConnectionStrings[name];
DbProviderFactory factory = DbProviderFactories.GetFactory(c.ProviderName);
using (IDbConnection connection = factory.CreateConnection())
{
    connection.ConnectionString = c.ConnectionString; 
    ... etc...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top