How to obtain database strings using ASP. NET
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:
Reference content is as follows:
- publicstringGetConnectionString(string_connectionStringsName)
- {
- SystemSystem.Configuration.ConnectionStringSettingsCollectionconfig=
- System.Configuration.ConfigurationManager.ConnectionStrings;
- for(inti=0;i<config.Count;i++)
- {
- if(config[i].Name.Equals(_connectionStringsName,StringComparison.OrdinalIgnoreCase))
- returnconfig[i].ToString();
- }
- returnString.Empty;
- }
If web. config is configured as follows:
Reference content is 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:
Reference 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. The above describes how to obtain the database string using ASP. NET.
- Analysis on PageBase and MasterPage of ASP. NET
- XML Web Service Method of ASP. NET
- Detailed description of ASP. NET environment deployment
- Implement ASP. NET globalization
- Solve the Problem of ASP. net ajax script errors