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 对象
基础教程推荐
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- c# Math.Sqrt 实现 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01