How to read the connection string from ASP.net 2.0

Source: Internet
Author: User

In asp.net 2.0, a new declarative expression syntax that resolves to a connection string value at run time is used, referencing the database connection string by name. The connection string itself is stored under the configuration section in the Web.config file so that it is easy to maintain for all pages in the application in a single location.

The

Sample program code is as follows:



Providername=" System.Data.SqlClient "/>
Integrated Security=true;database=northwind; Persist security info=true "
Providername=" System.Data.SqlClient "/>





Program code Description: In the program code of the example above, We set up two database connection strings under the configuration node in the Web.config file, pointing to the pubs and Northwind two sample databases respectively. Note that the data source control, such as the SqlDataSource Control, is introduced in 2.0, and we can set the ConnectionString property of the SqlDataSource control to the expression <%$ connectionstrings:pubs%>, The expression is parsed by the ASP.net parser into a connection string at run time. You can also specify an expression for the SqlDataSource ProviderName property, such as <%$ ConnectionStrings:Pubs.ProviderName%>. Its specific usage and new features will be described in detail in later chapters. Now there is a basic understanding can be.

Of course, we can also read the database connection string directly from the configuration file in the following way. First we need to reference the using System.Web.Configuration namespace, which contains the classes that are used to set up the ASP.net configuration.
String connectionString =configurationmanager.connectionstrings["Northwind"]. ConnectionString;
Program code Description: In the program code of the example above, we can use connectionstrings["Northwind" to read the corresponding Northwind string. Similarly, you can use connectionstrings["pubs" to read the corresponding pubs string.  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.