日期:2014-05-17  浏览次数:20882 次

求一个数据库连接类C#
若没有指定连接数据库字符串,则使用该连接,
从下面config.xml中读取数据库连接信息。
config.xml中格式大体如下。
  <set>
     <setting id ="default">
       <server>175.15.5.96</server>
       <user>sa</user>
       <password>root</password>
       <database>test</database>
     </setting>
  </set>
------最佳解决方案--------------------
web.congfig里面
  <?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
    <add key="connString" value="Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=Northwind;Data Source=ACS502-ROCKY"/>
</appSettings>
</configuration>

在代码中引用using System.Configuration;
OleDbConnection conn = null;
if(conn.ConnectionString=="")
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(Server.MapPath("config.xml"));
XmlNodeList xnl = xmlDoc.SelectNodes("set/setting");
foreach (XmlNode linkNode in xnl)
{
XmlElement xe = (XmlElement)linkNode;//将子节点类型转换为XmlElement类型
string aa = xe.SelectSingleNode("server").InnerText.Trim();
string bb = xe.SelectSingleNode("user").InnerText.Trim();
}

}else
{
 conn.ConnectionString=ConfigurationSettings.AppSettings["connString"];
}

------其他解决方案--------------------
判断connection的OleDbConnection是不是空,如果是,就用xmldocument读取xml内容,自己解析拼接
------其他解决方案--------------------
下面config.xml中读取数据库连接信息。使用下面方法:
、XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(Server.MapPath("config.xml"));
XmlNodeList xnl = xmlDoc.SelectNodes("set/setting");
foreach (XmlNode linkNode in xnl)
{
XmlElement xe = (XmlElement)linkNode;//将子节点类型转换为XmlElement类型
string aa = xe.SelectSingleNode("server").InnerText.Trim();
string bb = xe.SelectSingleNode("user").InnerText.Trim();
}
数据库类百度搜一个。
------其他解决方案--------------------
该回复于2012-12-04 13:23:27被管理员删除
------其他解决方案--------------------
微软的SQLhelper:http://wenku.baidu.com/view/ff74f319227916888486d7ab.html
------其他解决方案--------------------
public string GetConnstr()
{
 string str = File.ReadAllText("D:\\1.txt",Encoding.Default);
            return  Regex.Match( Regex.Replace(str, @"<(\w+)>([^<]+)</\1>\s*", "$1=$2;"),@"(\S+?;)+").Value;
}
------其他解决方案--------------------
能有点详细代码吗?我的c#还不是学的很好。感谢各位了
------其他解决方案--------------------
引用:
判断connection的OleDbConnection是不是空,如果是,就用xmldocument读取xml内容,自己解析拼接
麻烦您能写的详细一点吗?初学c#,不是很懂。