如何在不使用多个对象的情况下连接到VB.net中的OLEDB和ODBC

时间:2015-04-02 16:43:46

标签: vb.net ado.net odbc oledb

使用ADODB时,我能够使用连接字符串,该连接字符串是OLEDB提供程序或ODBC连接,并使用相同的连接对象。转换为ADO.NET并使用OleDB.OleDBConnection后,我发现您无法指定ODBC连接字符串,因为OLE DB的.NET Framework数据提供程序不支持OLE DB Provider for ODBC(MSDASQL)。我不想使用多个连接对象(System.Data.OLEDB和System.Data.ODBC)进行数据访问,因为我们的程序在数百个地方都有数据访问权限。人们如何在不使用多个连接对象的情况下允许连接数据库?谢谢!

1 个答案:

答案 0 :(得分:2)

您可以使用DbProviderFactory来抽象数据访问。它允许您为每个连接字符串对象获取正确连接类型的实例。

给出以下连接字符串配置:

<configuration>
  <connectionStrings>
    <clear/>
    <add name="NorthwindSQL" 
     providerName="System.Data.SqlClient" 
     connectionString=
     "Data Source=MSSQL1;Initial Catalog=Northwind;Integrated Security=true"
    />
    <add name="NorthwindAccess" 
     providerName="System.Data.OleDb" 
     connectionString=
     "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Data\Northwind.mdb;"
    />
    <add name="NorthwindODBC" 
     providerName="System.Data.Odbc"
     connectionString="Driver=ODBCDriver;server=ODBCServer;"
  </connectionStrings>
</configuration>

这将为您提供适当的连接:

//Read connection string
ConnectionStringSettings setting = ConfigurationManager.ConnectionStrings["NorthwindAccess"];

//Create connection
DbProviderFactory factory = DbProviderFactories.GetFactory(setting.ProviderName);
using(DbConnection connection = factory.CreateConnection())
{
    connection.ConnectionString = setting.ConnectionString;
    // Use the connection ...
    DbCommand command = connection.CreateCommand();
    // ...

}