In ASP.net 2.0, a more convenient configuration file access class is provided, which can be viewed under the System.Configuration namespace. This article provides a common way to get a database string in the development process, and write a method to make it easy to use:
public 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;
}
If the web.config is configured as follows:
<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>
If written as a static class method, you can invoke it using the following method:
String connectstring = xianhuimengutil.getconnectionstring ("ConnectionString1");
In addition, if you are traversing the output, you can see more than one configuration item, that is because the machine.config has the default definition of a database connection, the contents are as follows:
<connectionStrings>
<add name="LocalSqlServer" connectionString="data source=.SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename= DataDirectory aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" />
</connectionStrings>
This is what many netizens often ask in forums: why my program calls the SQLEXPRESS database, if your database is not configured correctly, or if you cannot open it, you will use the SQLEXPRESS database.