您所在的位置: 首页>>开发>>.Net>>asp.net>>

ASP.NET遍历配置文件的连接字符串

  • 摘要:本文提供一种在开发过程中常用的得到数据库字符串的方法,解答了一些程序会调用SQL EXPRESS数据库的原因,必如你的数据库配置不正确,或者无法打开时,就会使用SQL EXPRESS数据库。
  • 标签:ASP  .NET  SQL EXPRESS  字符串

在ASP.NET 2.0中,提供了更方便的配置文件访问的类,具体可以到System.Configuration名称空间下进行查看。本文提供一种在开发过程中常用的得到数据库字符串的方法,为方便使用,写成一个方法进行调用:

public string GetConnectionString( string _connectionStringsName )
{
System.Configuration.ConnectionStringSettingsCollection

config = System.Configuration.ConfigurationManager.ConnectionStrings;
for (int i = 0 ; i < config.Count ; i++)
{
if (config[i].Name.Equals(_connectionStringsName, StringComparison.OrdinalIgnoreCase))
return config[i].ToString();
}
return String.Empty;
}

如果web.config配置如下:

<connectionStrings>
<add name="ConnectionString1" connectionString="Persist Security Info=False;

User ID=sa;Password=;Initial Catalog=DataBase1;Server=(local);

" providerName="System.Data.SqlClient"/>
<add name="ConnectionString2" connectionString="Persist Security Info=False;

User ID=sa;Password=;Initial Catalog=DataBase2;Server=(local);

" providerName="System.Data.SqlClient"/>
</connectionStrings>

如果写成静态类方法,则可以使用下面的方法进行调用:

string ConnectString = XianhuiMengUtil.GetConnectionString("ConnectionString1");

另外,如果在遍历时进行输出,则可以看到多出来一个配置项,那是因为machine.config里已经默认定义理一个数据库连接,内容如下:

<connectionStrings>
<add name="LocalSqlServer" connectionString="data source=.SQLEXPRESS;

Integrated Security=SSPI;AttachDBFilename= DataDirectory aspnetdb.mdf;

User Instance=true" providerName="System.Data.SqlClient" />
</connectionStrings>

这就是许多网友在论坛上经常会问:为什么我的程序会调用SQL EXPRESS数据库的原因,如果你的数据库配置不正确,或者无法打开时,就会使用SQL EXPRESS数据库。

(责任编辑 火凤凰 sunsj@51cto.com  TEL:(010)68476636-8007)


专题:ASP.NET 2.0基础开发指南
.NET移动与嵌入式技术专题
.NET Framework新手入门专题
VS.NET实用开发专题
ADO.NET实用技巧专题
 
 验证码: (点击刷新验证码)   匿名发表
  • Visual C++ 完全自学宝典

  • 作者:强锋科技,朱洪波
  • Visual C++ 6.0是微软公司为程序人员提供的Visual Studio 6.0工具套件中的重要组成部分。本书由浅入深地介绍使用Visual C++ 6.0..
Copyright©2005-2008 51CTO.COM 版权所有