2

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?

user2743434
  • 104
  • 1
  • 8
  • Based on your connection string you should instantiate the connection class you need, the adapters and so on ... they are derived from the same base classes so except initialization your code can be the same. – Bogdan Apr 07 '14 at 06:22

1 Answers1

2

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...
}
Joe
  • 122,218
  • 32
  • 205
  • 338
  • Is there a way to read out tables that works for every data source? – user2743434 Apr 10 '14 at 13:38
  • 1
    @user2743434, there are differences in SQL dialect between data sources, and other differences such as the fact that OleDb uses positional parameters while SqlClient uses named parameters. So in general, your SQL will be provider-specific except in the simplest cases. – Joe Apr 10 '14 at 17:07