在實際項目裡,我們需要用一個應用程序去連接多個數據庫,有的進行測試,有的是數據庫基本結構相同,數據不同, 我們不可能總去程序的連接字符串裡去修改,更不能讓用戶去修改,所以需要動態去修改連接數據庫配置信息。如果安全性可考慮的話需要對字符串加密,我這裡寫點簡單的實現,希望大家有好的方法或意見,請執教和批評。
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文件,去獲取
數據庫連接。