如何构建基于 DbConnection提供商名称?
Sample 提供商名称s
- 系统.数据.SqlClient
- 系统.数据.OleDb
- 系统数据.ODBC
- FirebirdSql.Data.FirebirdClient
我的 IIS 服务器的 web.config 文件中存储有连接字符串:
<connectionStrings>
<add name="development"
connectionString="Provider = IBMDA400; Data Source = MY_SYSTEM_NAME; User Id = myUsername; Password = myPassword;"
providerName="System.Data.OleDb" />
<add name="live"
connectionString="usd=sa;pwd=password;server=deathstar;"
providerName="System.Data.Odbc" />
<add name="testing"
connectionString="usd=sa;pwd=password;server=deathstar;"
providerName="System.Data.SqlClient" />
<add name="offline"
connectionString="Server=localhost;User=SYSDBA;Password=masterkey;Charser=NONE;Database=c:\data\mydb.fdb"
providerName="FirebirdSql.Data.FirebirdClient"/>
您可以看到他们都使用不同的提供商。当我创建连接时,我必须知道要创建哪种 DbConnection,例如:
- sql连接
- OleDb连接
- Odbc连接
- Fb连接
连接字符串条目包含一个提供商名称,但这些不是 DbConnection 后代类的名称,但似乎是名称空间
我如何根据字符串构造 DbConnection提供商名称?
public DbConnection GetConnection(String connectionName)
{
//Get the connectionString infomation
ConnectionStringSettings cs =
ConfigurationManager.ConnectionStrings[connectionName];
if (cs == null)
throw new ConfigurationException("Invalid connection name \""+connectionName+"\");
//Create a connection based on the provider
DbConnection conn = new DbConnection();
}
如果您选择这条路线,我想您会想要使用 DbProviderFactories 类来获取可用于构造连接的 DbProviderFactory。我还没有尝试过这段代码,但我认为它会起作用。您可能需要使用 DbProviderFactories 类上的 GetFactoryClasses 方法查找提供程序名称并使用 InvariantName。
public DbConnection GetConnection(String connectionName)
{
//Get the connection string info from web.config
ConnectionStringSettings cs=
ConfigurationManager.ConnectionStrings[connectionName];
//documented to return null if it couldn't be found
if (cs == null)
throw new ConfigurationErrorsException("Invalid connection name \""+connectionName+"\"");
//Get the factory for the given provider (e.g. "System.Data.SqlClient")
DbProviderFactory factory =
DbProviderFactories.GetFactory(cs.ProviderName);
//Undefined behaviour if GetFactory couldn't find a provider.
//Defensive test for null factory anyway
if (factory == null)
throw new Exception("Could not obtain factory for provider \""+cs.ProviderName+"\"");
//Have the factory give us the right connection object
DbConnection conn = factory.CreateConnection();
//Undefined behaviour if CreateConnection failed
//Defensive test for null connection anyway
if (conn == null)
throw new Exception("Could not obtain connection from factory");
//Knowing the connection string, open the connection
conn.ConnectionString = cs.ConnectionString;
conn.Open()
return conn;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)