Database Connection is often used in programs, and database connection statements are indispensable. This is often the case in the past:
This method is to write the database connection to the program, which will cause trouble for future maintenance. Once you modify the database, you have to re-modify the code, package, and re-deploy the database, which requires a lot of work. now I have learned the object-oriented idea and have access to the configuration file app. config.
Specific Method:
1. Create an application configuration file.
2. open the file and enter the string to be connected in the file. the red box is the part to be added manually. Pay attention to the upper and lower correspondence. The <deleettings> is enabled, and a corresponding </deleetting> close statement is required, <add> also corresponds to </Add>.
Appsettings is used in the ASP. net1.1 period. In. NET Framework 2.0, connectionstrings is added.
1. <connectionstrings>
<Connectionstrings> <Add name = "connectionstringname" connectionstring = "Data Source = server name; initial catalog = database name; user id = user; Password = password" providername = "system. data. sqlclient "/> </connectionstrings>
2. <deleetask>
<Add key = "connectionstringname" value = "Data Source = server name or IP address; initial catalog = database name; persist Security info = false; user id = user; Password = password; packet size = 4096 "> </Add>
1) appsettings are commonly used in 2003 and connectionstrins are commonly used in 2005.
2) advantages of using connectionstring:
First, you can encrypt the connection string by using an encryption tool of Ms.
Second, data source controls that can be directly attached without having to write code to read them and then assign them to the controls.
Third, you can easily change the database platform. For example, if you change to an Oracle database, you only need to modify the providername.
3) Use System. configuration. configurationmanager. deleetask[ "name"] to retrieve the value in <deleetask>.
In <connectionstrings>, use system. configuration. configurationmanager. connectionstrings ["name"] to retrieve the value.
To show
3. Read files in program code
With this configuration file, you can directly open the config file (open with notepad) when you need to modify the database, or replace the configuration file. instead of redeployment. configuration files are more flexible than those written in the code, so database information is generally easier to modify, and more flexible things are written in the configuration file.