asp.net如何读取配置文件来获取数据库连接字符串

发布时间:2019-11-23编辑:脚本学堂
asp.net如何读取配置文件来获取数据库连接字符串

这里介绍一种在通过读取配置文件获取数据库连接字符串的方法

public static string GetConnectionString( string _connectionStringsName )
{
System.Configuration.ConnectionStringSettingsCollection config = System.Configuration.ConfigurationManager.ConnectionStrings;
for (int i = 0 ; i < config.Count ; i++)
{
if (config[i].Name.Equals(_connectionStringsName, StringComparison.OrdinalIgnoreCase))
return config[i].ToString();
}
return String.Empty;
}

web.config:
<connectionStrings>
<add name="ConnectionString1" connectionString="Persist Security Info=False;User ID=sa;Password=;Initial Catalog=DataBase1;Server=(local);" providerName="System.Data.SqlClient"/>
<add name="ConnectionString2" connectionString="Persist Security Info=False;User ID=sa;Password=;Initial Catalog=DataBase2;Server=(local);" providerName="System.Data.SqlClient"/>
</connectionStrings>

以静态方法调用:
string ConnectString = dataUtil.GetConnectionString("ConnectionString1");

如果在遍历时进行输出,则可以看到多出来一个配置项,是因为machine.config里已经默认定义理一个数据库连接,内容如下:
<connectionStrings>
<add name="LocalSqlServer" connectionString="data source=.SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=DataDirectory aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" />
</connectionStrings>