web.config中配置数据库连接字符串

<?xml version="1.0"?>
<!--
  有关如何配置 ASP.NET 应用程序的详细信息,请访问
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0"/>
  </system.web>
  <connectionStrings>
    <add name="conn" connectionString="Data Source=localhost;Initial Catalog=登陆模块;Integrated Security=True"/>
  </connectionStrings>
  <appSettings>
    <add key="conn" value="Data Source=(local);Database=登陆模块;Uid=sa;Pwd=xxxxx"/>
  </appSettings>
</configuration>

 1. 如上,可以将数据库字符串配置在<connectionStrings></connectionStrings>节中。推荐将数据库连接字符串定义在该节中。

  在.cs文件中调用该字符串的方法:

 string str=System.Configuration.ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
SqlConnection sqlstr = new SqlConnection(str);
//或者可以这样写
string str=System.Configuration.ConfigurationManager.ConnectionStrings["conn"].ToString();
SqlConnection sqlstr = new SqlConnection(str);

2. 也可以将数据库字符串配置在<appSettings></appSettings>节中,不推荐将数据库连接字符串定义在该节中。

  在.cs文件中调用该字符串的方法:

 string str=System.Configuration.ConfigurationManager.appSettings["conn"].ToString();
 SqlConnection sqlstr = new SqlConnection(str);

web.config中连接字符串的写法也有很多种:

其中:Data source 等价于Server 后面都是跟要连接的服务器名

如:Data source = (local)  或者 Data source = localhost  **注意**  (local)==localhost 而没有(localhost)和local这两种写法;

其中:Initial catalog等价于Database 后面都跟要连接的数据库名

如: Initial catalog = Login  或者 Database = Login

当连接字符串中出现Integrated Security=True或者SSPI时,连接语句中的 UserID, Pwd 是不起作用的,即采用windows身份验证模式。

原文地址:https://www.cnblogs.com/weicleer/p/2785089.html