此文章主要介紹的是Web.config正確配置SQL Server數(shù)據(jù)庫連接的實際擦步驟,在圖5-6中,選擇“添加新的啟用了調(diào)試的Web.config文件”單選按鈕,在圖5-6中,單擊“確定”按鈕后,在“解決方案資源管理器”對話框中可以看到。
在Web應(yīng)用程序的根目錄中創(chuàng)建了一個“Web.config”文件,如圖所示。
圖1.1 “未啟用調(diào)試”對話框
圖1.2生成“Web.config”文件
“Web.config”文件中提供的設(shè)置可以應(yīng)用于整個應(yīng)用程序,包括應(yīng)用程序的子目錄。在配置文件“Web.config”中,所有的配置信息都位于<configuration>和</configuration>XML根節(jié)點之間。
配置SQL Server數(shù)據(jù)庫連接
在“Web.config”文件中可以在<connectionStrings></connectionStrings>節(jié)點中配置SQL Server數(shù)據(jù)庫連接字符串,配置過程中使用的屬性如表所示。
下表是 配置SQL Server連接字符串使用的屬性
屬 性 說 明
Data Source 指定數(shù)據(jù)庫服務(wù)器名稱
Database 指定要連接的數(shù)據(jù)庫名
Uid 指定要登錄的數(shù)據(jù)庫服務(wù)器的用戶名
Pwd 指定要登錄的數(shù)據(jù)庫服務(wù)器的密碼
設(shè)置表5-7中的屬性連接數(shù)據(jù)庫時,采用的是SQL Server身份驗證。有時也采用Windows身份驗證,此時,需要配置SQL Server連接字符串使用的屬性為Data Source(指定數(shù)據(jù)庫服務(wù)器名)、Initial Catalog(指定要連接的數(shù)據(jù)庫名)、Integrated Security(指定是否采用集成Windows身份驗證)。
下面通過示例演示如何在“Web.config”文件中配置SQL Server數(shù)據(jù)庫連接,并在應(yīng)用程序中讀取配置信息。創(chuàng)建該示例的過程如下。
新建一個名為“Web configtest”的網(wǎng)站,默認的主頁名為“Default.aspx”。
在“Web.config”文件的<appSettings></appSettings>節(jié)點中添加如下代碼以連接SQL Server數(shù)據(jù)庫:
1
2
3
4
|
< appSettings > < add key = "sqlConn" value="Data Source = localhost ;Initial Catalog = pubs ; Integrated Security = True "/> </ appSettings > |
在頁面“Default.aspx”的“設(shè)計”視圖中添加一個GridView控件,用來顯示綁定到其上的數(shù)據(jù)。
在代碼隱藏文件“Default.aspx.cs”中添加代碼,將數(shù)據(jù)庫中的數(shù)據(jù)綁定到GridView控件上,代碼如下所示。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
using System; using System.Data.SqlClient; …… public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { String conn = ConfigurationManager.AppSettings["sqlConn"]; SqlDataAdapter sda = new SqlDataAdapter("select * from publishers", conn); DataSet ds = new DataSet(); sda.Fill(ds, "publishers"); GridView1.DataSource = ds.Tables["publishers"]; GridView1.DataBind(); } } |
以上的相關(guān)內(nèi)容就是對Web.config配置SQL Server數(shù)據(jù)庫連接的介紹,希望大家能有所收獲。