Fork me on GitHub

配置独立的数据库连接配置文件

我们需要把数据库连接独立的配置出来,以便我们使用

1、新建一个类文件,名称随意,不过最好是以Handler结尾的,因为要继承IConfigurationSectionHandler

 1 public class ConnHandler : IConfigurationSectionHandler
 2     {
 3 
 4         const string StrFormat = "server={0};database={1};uid={2};pwd={3}";
 5 
 6 
 7         #region IConfigurationSectionHandler 成员
 8 
 9         public object Create(object parent, object configContext, XmlNode node)
10         {
11             Hashtable tb = new Hashtable();
12 
13             foreach (XmlNode xn in node.ChildNodes)
14             {
15                 if (xn.NodeType == XmlNodeType.Element)
16                 {
              //JhEncrypt.Decrypt是自定义的解密算法,至于你要怎么加密那是你的事
17 string servre = JhEncrypt.Decrypt(xn.SelectNodes("server")[0].InnerText); 18 string database = JhEncrypt.Decrypt(xn.SelectNodes("database")[0].InnerText); 19 string user = JhEncrypt.Decrypt(xn.SelectNodes("user")[0].InnerText); 20 string password = JhEncrypt.Decrypt(xn.SelectNodes("password")[0].InnerText); 21 tb.Add(xn.Name, string.Format(StrFormat, servre, database, user, password)); 22 } 23 } 24 return tb; 25 26 } 27 28 #endregion 29 }

2、大家已经看到了,这需要定义一个xml文件了,然后xml文件需要有server, database, user, password节点,我们暂时把xml文件命名为“ConnDB.Config”

1 <ConnDB>
2   <DB>
3     <server>要加密的数据库实例</server>
4     <database>要加密的数据库</database>
5     <user>要加密的用户名</user>
6     <password>要加密的密码</password>
7   </DB>
8 </ConnDB>

3、该去Web.Config添加自定义的Section了

1 <configSections>
2     <section name="ConnDB" type="custom.ConnHandler"/>
3 </configSections>
4 <ConnDB configSource="ConnDB.config"/>

新建的section的Name一定要和下面声明的名字对应,type是命名空间.文件夹名称(可忽略).类名

下面声明的section配置节的configSource是新建的xml文件的名称

4、使用

页面加载的时候会读取web.config中自定义section配置节的内容,然后执行自定义Handler的Create方法从xml获取连接字符串内容存入HashTable中

调用的时候我们只要使用下面这句就可以从section中获取数据库连接字符串

Hashtable.Synchronized((Hashtable)ConfigurationManager.GetSection("ConnDB"));

Hashtable.Synchronized是为了线程安全考虑,

当然你也可以直接使用ConfigurationManager.GetSection("ConnDB")获取一个object对象转化为string

前提是你的xml中只有一个父节点下的子节点

posted @ 2017-03-23 12:15  雪山玉龙  阅读(345)  评论(0编辑  收藏  举报