1. Adding configuration Files
Create a new WinForm application, similar to Webfrom under a web.config,winform also has an app. config, but app. config is not auto-generated and needs to be added manually, right-click Project-〉 Add-〉 Add New Item-〉 add Application profile file [app. Config].
2, the configuration file is as follows
<?xml version= "1.0" encoding= "Utf-8"?>
<configuration>
<appSettings>
<add key= "ConnectionString" value= "Server=127.0.0.1;uid=sa;pwd=123456;database=power"/>
</appSettings>
</configuration>
3. Call in Project
private static string sql_conn_str = System.configuration.configurationsettings.appsettings["ConnectionString"];
4. Connect to the database
public static SqlConnection SqlConnection ()
{
Try
{
SqlConnection sqlconn = null;
string connstring = null;
connstring = db.dbconnectionstring;
Sqlconn = new SqlConnection (connstring);
Sqlconn.open ();
return sqlconn;
}
Catch
{
throw new Exception ("SQL Connection error!");
}
}
The above is a generic way to read the configuration file if we just want our configuration information to be applied to the database connection we have another way:
That is, in the case of <appSettings>, add <connectionStrings> tag configuration as follows:
<connectionStrings>
<add name= "CONNECTIONS" connectionString = "server=.;D Atabase=mydbtest; Uid=sa; Pwd=sa "/>
</connectionStrings>
That would be OK.
But the way you read it differs from the above:
Read mode:
String connectionstr = system.configuration.configurationmanager.connectionstrings["ConnectionStr"]. ConnectionString;
(to refer to the System.Configuration DLL file in the class first, it will prompt "ConfigurationManager does not exist")
With the above
<appSettings>
<add key = "value=" "/>
</appSettings>
The difference is:
Read mode:
String connectionstr = system.configuration.configurationsettings.appsettings["CONNECTIONS"];
WinForm database Connection app. Config file configuration