Asp.net is used as a website. If the database connection is configured on each page, you can imagine how headache the database connection string may change, you must traverse all database connection pages on the website to modify them! In this regard, the ideal way is to configure through web. config.
The following describes in detail how to configure:
First, declare the name of the configuration section and the name of the. NET Framework class that processes the configuration data in the section between the <configsections> and </configsections> labels at the top of the configuration file in Web. config.
Sample Code:
<! -- Database connection
-->
<Configsections>
<Section name = "Database" type = "system. Web. configuration. dictionarysectionhandler"/>
</Configsections>
Then, make the actual configuration settings for the declared section after the <configsections> area.
Sample Code:
<Database>
<Section key = "scon" value = "Server = localhost; uid = sa; Pwd =; database = mis_grad"/>
</Database>
The following describes how to access the Web. config file on the page.
You can access the Web. config file by using the configurationsettings. deleettings static string set.
Example: Obtain the connection string created in the preceding example
Dim sconstr as string = configurationsettings. deleettings ("sconstr ")
Dim scon as new sqlconnection (sconstr)
There is no problem with this, but there is a problem during debugging:
The connectionstring property has not been initialized.
Note:An error occurred while executing the current Web request. Check the stack trace information for details about the error and the source of the error in the code.
Exception details:System. invalidoperationexception: The connectionstring property has not been initialized.
I have not solved this problem yet. Ask the expert for advice:
I have seen many comrades scold me. Actually, I did the right thing, but I made a mistake.
Dim sconstr as string = configurationsettings. deleettings ("sconstr ")
It should be dim sconstr as string = configurationsettings. deleettings ("scon ")
It took me a long time to solve this problem.
So dizzy ........................
What I wrote is too complex, as long:
<Deleetask>
<Section key = "scon" value = "Server = localhost; uid = sa; Pwd =; database = mis_grad"/>
</Appsettings>
You can.