C# 通过连接字符串检索正确的 DbConnection 对象

C# Retrieving correct DbConnection object by connection string(C# 通过连接字符串检索正确的 DbConnection 对象)
本文介绍了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# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
quot;Overflowquot; compiler error with -9223372036854775808L(编译器错误-9223372036854775808L(Q;溢出Q))
Visual Studio 2010 ReportViewer Assembly References(Visual Studio 2010 ReportViewer程序集引用)
Weird behaviour when I open a reportviewer in WPF(在WPF中打开报表查看器时出现奇怪的行为)
how do i pass parameters to aspnet reportviewer(如何将参数传递给aspnet report查看器)