ASP. NET 2.0 provides a more convenient class for accessing Configuration files. For details, see the System. Configuration namespace. This article provides a method that is commonly used in the development process to obtain database strings. For ease of use, write a method for calling:
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 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 you write static class methods, you can use the following method to call them:
string ConnectString = XianhuiMengUtil.GetConnectionString("ConnectionString1");
|
In addition, if output is performed during traversal, an additional configuration item is displayed because a database connection is defined by default in machine. config. The content is 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 why many netizens often ask on the Forum: Why does my program call the SQL EXPRESS database? If your database configuration is incorrect or cannot be enabled, the SQL EXPRESS database is used.