我有一个连接字符串传递给一个函数,我需要基于这个字符串创建一个基于DbConnection的对象(即SQLConnection,OracleConnection,OLEDbConnection等).
是否有任何内置功能可以执行此操作,或任何第三方库可以提供帮助.我们不一定要构建这个连接字符串,所以我们不能依赖于写入字符串的格式来确定它的类型,我宁愿不必编写可能的连接字符串的所有组合和排列
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() .FirstOrDefault(x=>x.ConnectionString==connStr); if (css != null) providerName = css.ProviderName; } if (providerName != null) { var providerExists = DbProviderFactories .GetFactoryClasses() .Rows.Cast () .Any(r=>r[2].Equals(providerName)); if (providerExists) { var factory = DbProviderFactories.GetFactory(providerName); var dbConnection = factory.CreateConnection(); dbConnection.ConnectionString = connStr; return dbConnection; } } return null; }
如果您使用的是框架2.0或更高版本,并且可以让它们使用驱动程序类传递第二个字符串,则可以使用dbProviderFactory类为您加载驱动程序.
DbProviderFactory dbProviderFactory = DbProviderFactories.GetFactory(myDriverClass); DbConnection dbConnection = dbProviderFactory.CreateConnection(); dbConnection.ConnectionString = myConnectionString;
这是工厂类的MSDN链接:http: //msdn.microsoft.com/en-us/library/wda6c36e.aspx