(i) WinForm application:
(1) Create a new configuration file, app. Config:
<?xml version= "1.0" encoding= "Utf-8"?>
<configuration>
<appSettings>
<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>
Select one of the two nodes in the appsettings and connectionstrings.
If you are connecting 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>
<appSettings>
<add key= "ConnectionString" value= "server=.\sqlexpress;database=phonebook;uid=sa;pwd=12345678"/>
</appSettings>
</configuration>
In fact, there is a persist Security info attribute in the above connection string, which means whether to save the security information, in fact, it can be simply understood as "whether to save the password information after the database connection succeeds", True to save, false to not save. Ado. NET defaults to False.
If the database is not attached to the database server, you can place the database file in the App_Data directory of the Web site and use AttachDbFileName to indicate the database file:
<add name= "phonebookconnectionstring" connectionstring= "Data source=.\sqlexpress;integrated Security=True; attachdbfilename=| datadirectory| Phonebook.mdf; User instance=true "/>
(2) Adding reference System.Configuration, introducing the namespace using System.Configuration of the configuration class;
(3) Using the Configuration Management Class (ConfigurationManager) to read the connection string
String connstr=configurationmanager.connectionstrings["ConnStr"]. ConnectionString;
If appsettings is used in the configuration file, the read code is:
String connstr=configurationmanager.appsettings["ConnStr"]
(ii) ASP. NET Application
To 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:
<appSettings>
<add key= "TXL" value= "Provider=Microsoft.Jet.OLEDB.4.0;Data source=| Datadirectory|\txl.mdb "/>
</appSettings>
| Datadirectory| represents the App_Data folder under the root directory of the Web site.
Read the method with the WinForm application.
Note: It is recommended that the connection string be encrypted in the configuration file in the actual project and then decrypted after reading.
. NET configuration file, use the database connection string in the