在C# config文件中保存數據庫連接字符串

.NET配置文件中的连接字符串
不推薦在web.config中使用appSettings部分。而是使用web.config中的connectionStrings部分。

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
  </connectionStrings>
</configuration>  

要将连接字符串读入代码中,请使用ConfigurationManager类。

string connStr = ConfigurationManager.ConnectionStrings[“myConnectionString”].ConnectionString;
记住要添加对System.Configuration组件的引用。然后包括名称空间System.Configuration以获得对ConfigurationManager类的访问。

// C#
using System.Configuration;

// VB.Net
imports System.Configuration
清除来自高级配置文件的连接字符串
配置文件是分层的,其中machine.config位于最高级别。您可以清除在层次结构中较早定义的连接字符串,以确保任何不需要的设置不会冒泡达到所需的值。

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
   <clear /> <!-- clear all other connection strings -->
   <add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
  </connectionStrings>
</configuration>

通常,在connectionStrings部分的顶部添加是确保没有其他连接字符串从更高级别的配置文件冒泡的好习惯。

.NET 2.0配置文件之前的连接字符串
仅对旧的.NET 1.0和.NET 1.1应用程序使用此信息。在appSettings位置中,添加一个名为您想要引用连接字符串的键。

<appSettings>
  <add key="myConnectionString" value="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</appSettings>

要从代码读取连接字符串,请使用ConfigurationSettings类。

string connStr = ConfigurationSettings.AppSettings(“myConnectionString”);
现在,您已将连接字符串从web.config加载到代码中的字符串变量中。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值