今天在做關於winfrom連接數據庫的時候,遇到一個問題:在這里沒有像.net bs模式中那樣直接在配置文件中填寫連接數據庫語句,那么,如果有沒有一種比較好的方式,實現向bs模式中的那樣,可以很方便容易的改變連接數據庫語句。答案就在app.config文件中。
首先新建一個xml文件,取名為app.config,在里面填寫連接數據庫語句:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings/>
<appSettings>
<add key="Conn" value="server=.;uid=sa;pwd=123;database=PM_Information"/>
</appSettings>
</configuration>
然后再需要連接數據庫的文件中讀取配置文件中的信息。
using System.Xml;
public static string ReadXml()
{
XmlDocument doc = new XmlDocument();
string strFileName = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
doc.Load(strFileName);
XmlNode node = doc.SelectSingleNode("configuration/appSettings/add");
return node.Attributes[1].Value;
}
