(i) WinForm applications:
(1) 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>
AppSettings and connectionstrings choose one of these two nodes.
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 also a persist Security info attribute in the above connection string, which means that you can simply read "Save password information after a successful database connection", meaning save, false means no 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 of the configuration class using System.Configuration;
(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 applications
Add nodes to the configuration file Web.config:
<connectionstrings>
<add name= "TXL" Provider=Microsoft.Jet.OLEDB.4.0;Data source=| Datadirectory|\txl.mdb "/>
</connectionstrings>
or add nodes:
<appsettings>
<add key=" TXL "value=" Provider=Microsoft.Jet.OLEDB.4.0;Data source=| Datadirectory|\txl.mdb "/>
</appsettings>
| Datadirectory| represents the App_Data folder in the root directory of the Web site. The
Read method is the same as the WinForm application.
Note: It is recommended that the connection string be encrypted, read, and decrypted in the configuration file when used in the actual project.