[英]Dynamically Provide Username and password to Connection String
I am using C# winform application using MySql as back-end database. 我正在使用将MySql用作后端数据库的C#winform应用程序。 Using App.config file, application read connection string to connect database as follows:
使用App.config文件,应用程序读取连接字符串以连接数据库,如下所示:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionstring>
<addkey="MySQL.DB"value="server=localhost;database=mysqldbname;user=username;password=12345678;">
</add>
</connectionstring>
</configuration>
Is there any way that we can provide username and password not from App.config but from user of application, by entering username and password? 有什么方法可以通过输入用户名和密码而不是从App.config中而是从应用程序的用户中提供用户名和密码? so that we are able to protect sensitive data.
这样我们就可以保护敏感数据。 Other information are ok to read from app.config like database name, server etc.
可以从app.config中读取其他信息,例如数据库名称,服务器等。
Ahmed 艾哈迈德
you can have appSettings
你可以有
appSettings
<appSettings>
<add key="ConFormat" value="server=localhost;database=mysqldbname;user={0};password={1};"/>
</appSettings>
read it and set the values 读取并设置值
var formatString = ConfigurationManager.AppSettings["ConFormat"].ToString();
var conString = string.Format(formatString , SecureUserName, SecurePW);
If you're using raw ADO.NET then you can use a connection string builder, presumably a MySqlConnectionStringBuilder in your case. 如果您使用的是原始ADO.NET,则可以使用连接字符串构建器,在您的情况下可能使用MySqlConnectionStringBuilder。 Create a new instance with the connection string from the config file, set the appropriate properties and then get the result from the ConnectionString property.
使用配置文件中的连接字符串创建一个新实例,设置适当的属性,然后从ConnectionString属性获取结果。
By the way, you can store passwords and other sensitive data in the config file using Protected Configuration to encrypt it. 顺便说一句,您可以使用“受保护的配置”将密码和其他敏感数据存储在配置文件中以对其进行加密。
Change the code in app.config like this 像这样更改app.config中的代码
<add key="MySQL.DB"value="server=localhost;database=mysqldbname;user=&usernamefromuser;password=&passfromuser;">
Add a button for connecting and 2 textboxes for username and password 添加一个用于连接的按钮和2个用于输入用户名和密码的文本框
Buttons code : 按钮代码:
//other code for mysql variables ...
string connectionStr= connStrFrom_App_Config.Replace("&usernamefromuser",texBox1.Text).Replace("&passfromuser",textBox2.Text);
//other code for connecting
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.