问题描述
我有一个连接字符串被传递给一个函数,我需要基于这个字符串创建一个基于 DbConnection 的对象(即 SQLConnection、OracleConnection、OLEDbConnection 等).
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
推荐答案
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;
}
这篇关于C# 通过连接字符串检索正确的 DbConnection 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!