C# Retrieving correct DbConnection object by connection string(C# 通过连接字符串检索正确的 DbConnection 对象)
问题描述
我有一个连接字符串被传递给一个函数,我需要基于这个字符串创建一个基于 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 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# 通过连接字符串检索正确的 DbConnection 对象
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- 使用 rss + c# 2022-01-01