(1) winform application:
(1) create a configuration file app. config:
<? XML version = "1.0" encoding = "UTF-8"?>
<Configuration>
<Deleetask>
<Add key = "connstr" value = "provider = Microsoft. Jet. oledb.4.0; Data Source = F: \ C # code \ dboperation \ ykjj. mdb"/>
</Appsettings>
<Connectionstrings>
<Add name = "connstr" connectionstring = "provider = Microsoft. Jet. oledb.4.0; Data Source = F: \ C # code \ dboperation \ ykjj. mdb"/>
</Connectionstrings>
</Configuration>
You can select one of the appsettings and connectionstrings nodes.
If you connect to SQL Server, the configuration file is:
<? XML version = "1.0" encoding = "UTF-8"?>
<Configuration>
<Connectionstrings>
<Add name = "phonebookconnectionstring"
Connectionstring = "Data Source =. \ sqlexpress; initial catalog = phonebook; user id = sa; Password = 12345678"
Providername = "system. Data. sqlclient"/>
</Connectionstrings>
<Deleetask>
<Add key = "connectionstring" value = "Server =. \ sqlexpress; database = phonebook; uid = sa; Pwd = 12345678"/>
</Appsettings>
</Configuration>
The above connection string actually has a persist Security info attribute, which indicates whether to save the security information. In fact, it can be simply understood as "whether to save the password information after the database connection is successful ", true indicates saving, and false indicates not saving. The default value of ADO. NET is false.
If the database is not attached to the database server, you can put the database file under the app_data directory of the website and use attachdbfilename to specify the database file:
<Add name = "phonebookconnectionstring" connectionstring = "Data Source =. \ sqlexpress; Integrated Security = true; attachdbfilename = | datadirectory | phonebook. MDF; user instance = true"/>
(2) Add and reference system. configuration, and introduce the configuration class namespace using system. configuration;
(3) Use the configuration management class (configurationmanager) to read the connection string
String connstr = configurationmanager. connectionstrings ["connstr"]. connectionstring;
If the configuration file uses deleettings, the read code is:
String connstr = configurationmanager. receivettings ["connstr"]
(2) ASP. NET Applications
Add a node to the configuration file web. config:
<Connectionstrings>
<Add name = "TXL" connectionstring = "provider = Microsoft. Jet. oledb.4.0; Data Source = | datadirectory | \ TXL. mdb"/>
</Connectionstrings>
Or add a node:
<Deleetask>
<Add key = "TXL" value = "provider = Microsoft. Jet. oledb.4.0; Data Source = | datadirectory | \ TXL. mdb"/>
</Appsettings>
| Datadirectory | the app_data folder under the root directory of the website.
The read method is the same as that of the winform application.
Note: We recommend that you encrypt the connection string in the configuration file and decrypt it after reading it.