大佬教程收集整理的这篇文章主要介绍了ado.net – ASP.NET:如何从web.config ConnectionString创建一个连接?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
示例提供商名称
> System.Data.SqlClient
> System.Data.oleDb
> System.Data.odbc
> FirebirdSql.Data.FirebirdClient
我有连接字符串存储在我的IIS服务器的web.config文件中:
<connectionStrings> <add name="development" connectionString="Provider = IBMDA400; Data source = MY_SYSTEM_NAME; User Id = myUsername; password = mypassword;" providerName="System.Data.oleDb" /> <add name="live" connectionString="usd=sa;pwd=password;server=deathstar;" providerName="System.Data.odbc" /> <add name="tesTing" connectionString="usd=sa;pwd=password;server=deathstar;" providerName="System.Data.SqlClient" /> <add name="offline" connectionString="Server=localhost;User=SYSDBA;password=masterkey;Charser=NONE;Database=c:\data\mydb.fdb" providerName="FirebirdSql.Data.FirebirdClient"/>
你可以看到他们都使用不同的提供者.当我来创建一个连接的时候,我必须知道要创建什么样的DbConnection,例如:
> SqlConnection
> OleDbConnection
> OdbcConnection
> FbConnection
connectionStrings条目包含一个providerName,但这些不是DbConnection后代类的名称,而是一个命名空间
我如何根据字符串providerName构建一个DbConnection?
public DbConnection GetConnection(String connectionName) { //Get the connectionString infomation ConnectionStringSetTings cs = ConfigurationManager.ConnectionStrings[connectionName]; if (cs == null) throw new ConfigurationException("Invalid connection name \""+connectionName+"\"); //Create a connection based on the provider DbConnection conn = new DbConnection(); }
public DbConnection GetConnection(String connectionName) { //Get the connection String info from web.config ConnectionStringSetTings cs= ConfigurationManager.ConnectionStrings[connectionName]; //documented to return null if it couldn't be found if (cs == null) throw new ConfigurationErrorsException("Invalid connection name \""+connectionName+"\""); //Get the factory for the given provider (e.g. "System.Data.SqlClient") DbProviderFactory factory = DbProviderFactories.GetFactory(cs.ProviderName); //Undefined behaviour if GetFactory couldn't find a provider. //Defensive test for null factory anyway if (factory == null) throw new Exception("Could not obtain factory for provider \""+cs.ProviderName+"\""); //Have the factory give us the right connection object DbConnection conn = factory.CreateConnection(); //Undefined behaviour if CreateConnection failed //Defensive test for null connection anyway if (conn == null) throw new Exception("Could not obtain connection from factory"); //Knowing the connection String,open the connection conn.ConnectionString = cs.ConnectionString; conn.open() return conn; }
以上是大佬教程为你收集整理的ado.net – ASP.NET:如何从web.config ConnectionString创建一个连接?全部内容,希望文章能够帮你解决ado.net – ASP.NET:如何从web.config ConnectionString创建一个连接?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。