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身份驗證模式。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM