按一下以給予評分及指教
TechNet

  開啟低頻寬檢視
ASP.NET
HOW TO:使用 SqlDataSource 控制項連接至 SQL 資料庫

您可以使用 SqlDataSource 控制項連接至 Microsoft SQL Server 資料庫。如果要連接至資料庫,您需要連接字串和 SQL Server 資料庫的存取權限。然後,您可以使用 SqlDataSource 控制項,將資料提供給任何支援 DataSourceID 屬性的資料繫結控制項,例如 GridView 控制項。

若要在 Web.config 檔案中設定 SQL Server 的連接字串

  1. 開啟 ASP.NET 應用程式根目錄中的 Web.config 檔。如果沒有 Web.config 檔案,請建立一個。

  2. Configuration 項目中,如果 ConnectionStrings 項目不存在,請加入一個該項目。

  3. 建立 add 項目當做 ConnectionStrings 項目的子系,並定義下列屬性:

    • name:將值設定為您要用來參考連接字串的名稱,如下列範例所示:

      name="CustomerDataConnectionString"
    • connectionString:指派使用 SQL Server 位置和驗證資訊的連接字串 (如果適用的話)。連接字串應如下所示:

      connectionString="Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind"
      Note注意事項

      如果您使用 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>
  4. 儲存並關閉 Web.config 檔案。

若要從 SqlDataSource 控制項參考 SQL Server 連接字串

  1. 在想要連接至 SQL Server 資料庫的網頁中,加入 SqlDataSource 控制項。

  2. 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 控制項。

請參閱

社群內容   什麼是社群內容?
新增內容 RSS  註解
Processing
© 2009 Microsoft Corporation. 著作權所有,並保留一切權利。 使用規定  |  商標  |  隱私權聲明
Page view tracker