How to Configure Database Connections in web. config

  • 2021-07-07 06:58:21
  • OfStack

In website development, Database operations are often used, The general practice in ASP. NET is to configure the database connection code in web. config, and then call the database connection code in the program. The advantage of this is that when the database connection code needs to be changed, we only need to modify the database connection code in web. config, instead of modifying the database connection code in every 1 page.

There are two ways to configure database connection code in ASP. NET, appSettings and connectionStrings. When you use appSettings and connectionStrings to configure the database connection code, you can use the < configuration > Add the following code below:

1. appSettings


<appSettings>  
<add key="conn" value="server= Server name ;database= Database name ;uid= User name ;password= Password ;"/> 
</appSettings> 

2. connectionStrings


<connectionStrings>  
<add name="conn"  
connectionString="Dserver= Server name ; 
database= Database name ;uid= User name ;password= Password " providerName="System.Data.SqlClient" /> 
</connectionStrings> 

Differences between appSettings and connectionStrings:

(1) appSettings is commonly used in 2003, connectionStrings is commonly used in 2005;

(2) Benefits of using connectionStrings:

First, the connection string can be encrypted by using one encryption tool of MS;

Second, you can bind the data source control directly, instead of writing code to read it and assign it to the control;

Third, the database platform can be easily replaced, such as Oracle database, only need to modify providerName.

(3) Write in appSettings and use System. Configuration. ConfigurationManager. AppSettings ["keyname"] to obtain the database connection code value; Write in connectionStrings to get the database connection code value with System. Configuration. ConfigurationManager. ConnectionStrings ["name"].

I hope you will gain something from this article's introduction to the two ways of configuring database connections in web. config and these two ways.


Related articles: