在实际项目里,我们需要用一个应用程序去连接多个数据库,有的进行测试,有的是数据库基本结构相同,数据不同,我们不可能总去程序的连接字符串里去修改,更不能让用户去修改,所以需要动态去修改连接数据库配置信息。如果安全性可考虑的话需要对字符串加密,我这里写点简单的实现,希望大家有好的方法或意见,请执教和批评。
1 在应用程序里添加app.config
<?xmlversion="1.0"encoding="utf-8"?>
<configuration>
<appSettings>
<!--Userapplicationandconfiguredpropertysettingsgohere.-->
<!--Example:<addkey="settingName"value="settingValue"/>-->
<addkey="ServerIP"value="127.0.0.1"/>
<addkey="Server"value="Automation_temp"></add>
<addkey="user"value="sa"></add>
<addkey="password"value="shan"></add>
</appSettings>
</configuration>
程序读取数据库连接,如下:
如果想把连接的信息显示出来,可以去解析字符串strcon,获取相关信息
privatevoidOpen()
{
//openconnection
if(con==null)
{
stringstrcon=String.Format("packetsize=4096;datasource={0};persistsecurityinfo=True;initialcatalog={1};userid={2};password={3}",ConfigurationSettings.AppSettings["SQLserverIP"],
ConfigurationSettings.AppSettings["Server"],ConfigurationSettings.AppSettings["user"],ConfigurationSettings.AppSettings["password"]);
con=newSqlConnection(strcon);
try
{
con.Open();
}
catch(Exceptionee)
{
ee.ToString();
}
}
}
2 新建窗体ConfigFrm
添加4个label ,分别是:
服务器ip,Database Name,SA,password,
4个TextBox,分别是:
txtIP
txtDataBaseName
txtName
txtPwd
1个确认按钮btnOK,
3 写个方法保存修改的设置:
privatevoidSaveConfig(stringConnenctionString,stringstrKey)
{
XmlDocumentdoc=newXmlDocument();
//获得配置文件的全路径
stringstrFileName=AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
doc.Load(strFileName);
//找出名称为“add”的所有元素
XmlNodeListnodes=doc.GetElementsByTagName("add");
for(inti=0;i<nodes.Count;i++)
{
//获得将当前元素的key属性
XmlAttributeatt=nodes[i].Attributes["key"];
//根据元素的第一个属性来判断当前的元素是不是目标元素
if(att.Value==strKey)
{
//对目标元素中的第二个属性赋值
att=nodes[i].Attributes["value"];
att.Value=ConnenctionString;
break;
}
}
//保存上面的修改
doc.Save(strFileName);
}
4 在确认按钮btnOK click事件:
privatevoidbtnOK_Click(objectsender,System.EventArgse)
{
if(txtIP.Text=="")
{
MessageBox.Show("ServerIPisnotallownull");
return;
}
elseif(txtDataBaseName.Text=="")
{
MessageBox.Show("DataBaseisnotallownull");
return;
}
elseif(txtName.Text=="")
{
MessageBox.Show("UserNameisnotallownull");
return;
}
else
{
SaveConfig(txtIP.Text,"ServerIP");
SaveConfig(txtDataBaseName.Text,"Server");
SaveConfig(txtName.Text,"user");
SaveConfig(txtPassword.Text,"password");
MessageBox.Show("ConfigSucessful!","",MessageBoxButtons.OK,MessageBoxIcon.Warning);
}
this.Close();
}
在应用程序当前目录下,程序动态加载的是 /bin/debug/test.exe.config信息,从而实现了动态读写xml文件,去获取
数据库连接。