In ASP. NET 2.0, a new declarative expression syntax is used to parse a connection string value at runtime, referencing the database connection string by name. The connection string is stored under the <connectionStrings> Configuration section in the Web. config file to facilitate maintenance of all pages in the application at a single location.
The sample code is as follows: <? Xml version = "1.0"?> <Configuration> <connectionStrings> <add name = "Pubs" connectionString = "Server = localhost; Integrated Security = True; Database = pubs; Persist Security Info = True" providerName = "System. data. sqlClient "/> <add name =" Northwind "connectionString =" Server = localhost; Integrated Security = True; Database = Northwind; Persist Security Info = True "providerName =" System. data. sqlClient "/> </connectionStrings> <system. web> <pages styleSheetTheme = "Default"/> </system. web> </configuration>
Program Code Description: In the program code of the preceding example. under the <connectionStrings> Configuration node in the Config file, two database connection strings are set, pointing to the pubs and Northwind sample databases respectively. Note that a data source control is introduced in 2.0, such as the SqlDataSource control. We can set the ConnectionString attribute of the SqlDataSource control to an expression <% $ ConnectionStrings: Pubs %>, this expression is run by ASP.. NET analyzer is parsed as a connection string. You can also specify an expression for the ProviderName attribute of SqlDataSource, for example, <% $ ConnectionStrings: Pubs. ProviderName %>. The specific usage and new features will be detailed in the subsequent sections. Now you have a basic understanding. Of course, we can also use the following method to directly read the database connection string from the configuration file. First, we need to reference the using System. Web. Configuration namespace, which contains classes used to set ASP. NET configurations. String connectionString = ConfigurationManager. ConnectionStrings ["Northwind"]. ConnectionString;
Program Code Description: In the program code of the preceding example, we can use ConnectionStrings ["Northwind"] to read the corresponding Northwind string. Similarly, you can use ConnectionStrings ["Pubs"] to read the corresponding Pubs string.