在实际项目里,我们需要用一个应用程序去连接多个数据库,有的进行测试,有的是数据库基本结构相同,数据不同, 我们不可能总去程序的连接字符串里去修改,更不能让用户去修改,所以需要动态去修改连接数据库配置信息。如果安全性可考虑的话需要对字符串加密,我这里写点简单的实现,希望大家有好的方法或意见,请执教和批评。
1 在应用程序里添加app.config
<?
xml version="1.0" encoding="utf-8"
?>
<
configuration
>
<
appSettings
>
<!--
User application and configured property settings go here.
-->
<!--
Example: <add key="settingName" value="settingValue"/>
-->
<
add
key
="ServerIP"
value
="127.0.0.1"
/>
<
add
key
="Server"
value
="Automation_temp"
></
add
>
<
add
key
="user"
value
="sa"
></
add
>
<
add
key
="password"
value
="shan"
></
add
>
</
appSettings
>
</
configuration
>
程序读取数据库连接,如下:
如果想把连接的信息显示出来,可以去解析字符串strcon,获取相关信息
private
void
Open()

...
{
// open connection
if (con == null)

...{
string strcon=String.Format ("packet size=4096;data source={0};persist security info=True;initial catalog={1};user id={2};password={3}",ConfigurationSettings.AppSettings["SQLserverIP"],
ConfigurationSettings.AppSettings["Server"],ConfigurationSettings.AppSettings["user"],ConfigurationSettings.AppSettings["password"]);
con = new SqlConnection(strcon);
try

...{
con.Open();
}
catch(Exception ee)

...{
ee.ToString();
}
}
}
2 新建窗体ConfigFrm
添加4个label ,分别是:
服务器ip,Database Name,SA,password,
4个TextBox,分别是:
txtIP
txtDataBaseName
txtName
txtPwd
1个确认按钮btnOK,
3 写个方法保存修改的设置:
private
void
SaveConfig(
string
ConnenctionString,
string
strKey)

...
{
XmlDocument doc=new XmlDocument();
//获得配置文件的全路径
string strFileName=AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
doc.Load(strFileName);
//找出名称为“add”的所有元素
XmlNodeList nodes=doc.GetElementsByTagName("add");
for(int i=0;i<nodes.Count;i++)

...{
//获得将当前元素的key属性
XmlAttribute att=nodes[i].Attributes["key"];
//根据元素的第一个属性来判断当前的元素是不是目标元素
if (att.Value==strKey)

...{
//对目标元素中的第二个属性赋值
att=nodes[i].Attributes["value"];
att.Value=ConnenctionString;
break;
}
}
//保存上面的修改
doc.Save(strFileName);
}
4 在确认按钮btnOK click事件:
private
void
btnOK_Click(
object
sender, System.EventArgs e)

...
{
if (txtIP.Text=="")

...{
MessageBox.Show("ServerIP is not allow null");
return ;
}
else if(txtDataBaseName.Text=="")

...{
MessageBox.Show("DataBase is not allow null");
return ;
}
else if(txtName.Text=="")

...{
MessageBox.Show("User Name is not allow null");
return ;
}
else

...{
SaveConfig(txtIP.Text,"ServerIP");
SaveConfig(txtDataBaseName.Text,"Server");
SaveConfig(txtName.Text,"user");
SaveConfig(txtPassword.Text,"password");
MessageBox.Show("Config Sucessful!","",MessageBoxButtons.OK,MessageBoxIcon.Warning);
}
this.Close();
}
在应用程序当前目录下,程序动态加载的是 /bin/debug/test.exe.config信息,从而实现了动态读写xml文件,去获取
数据库连接。