您可以使用 SqlDataSource 控制項連接至 Microsoft SQL Server 資料庫。如果要連接至資料庫,您需要連接字串和 SQL Server 資料庫的存取權限。然後,您可以使用 SqlDataSource 控制項,將資料提供給任何支援 DataSourceID 屬性的資料繫結控制項,例如 GridView 控制項。
開啟 ASP.NET 應用程式根目錄中的 Web.config 檔。如果沒有 Web.config 檔案,請建立一個。
在 Configuration 項目中,如果 ConnectionStrings 項目不存在,請加入一個該項目。
建立 add 項目當做 ConnectionStrings 項目的子系,並定義下列屬性:
name:將值設定為您要用來參考連接字串的名稱,如下列範例所示:
name="CustomerDataConnectionString"
connectionString:指派使用 SQL Server 位置和驗證資訊的連接字串 (如果適用的話)。連接字串應如下所示:
connectionString="Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind"
如果您使用 Windows 整合式驗證連接至 SQL Server,就需要確定擁有適當的 SQL Server 資料庫存取權之 Web 應用程式的識別。如需判斷 Web 應用程式識別的資訊,請參閱 ASP.NET 模擬。
providerName 指派值 "System.Data.SqlClient",此值會指定 ASP.NET 在使用此連接字串進行連接時,應該使用 ADO.NET 提供者 System.Data.SqlClient。
連接字串組態與下列程式碼相似:
<connectionStrings> <add name="CustomerDataConnectionString" connectionString="Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind" providerName="System.Data.SqlClient" /> </connectionStrings>
儲存並關閉 Web.config 檔案。
在想要連接至 SQL Server 資料庫的網頁中,加入 SqlDataSource 控制項。
在 SqlDataSource 控制項中,設定下列屬性:
SelectCommand:設定為用來擷取資料的 SQL select 陳述式,如下列範例所示:
SelectCommand="Select CustomerID, CompanyName From Customers"
ConnectionString:設定為在 Web.config 檔中建立的連接字串名稱,格式為 <%$ ConnectionStrings: connection string name %>。
下列範例示範了設定為連接至 SQL Server 資料庫的 SqlDataSource 控制項。
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:CustomerDataConnectionString %>" SelectCommand="SELECT CustomerID, CompanyName FROM Customers" />
您現在可以將其他控制項 (例如 GridView 控制項) 繫結至 SqlDataSource 控制項。