使用 SqlDataSource 控制項選取資料

更新:2007 年 11 月

您可以在使用少許或不需使用程式碼的情況下,使用 SqlDataSource 控制項擷取資料庫的資料。SqlDataSource 控制項可以使用在組態的 DbProviderFactories 區段中有設定關聯 ADO.NET 提供者的任何資料庫,包括 Microsoft SQL Server、Oracle, ODBC 或像是 Microsoft Access 的 OLE DB 資料庫。您使用的資料庫會規定 SqlDataSource 設定使用的 SQL 陳述式語法,以及是否可使用像是預存程序的其他進階資料庫功能。然而,資料來源控制項在所有資料庫上的作業方式都相同。

若要使用 SqlDataSource 控制項擷取資料庫的資料,至少需要設定下列屬性:

  • ProviderName 設定為代表正在使用之資料庫的 ADO.NET 提供者名稱。如果您使用 Microsoft SQL Server,請將 ProviderName 屬性設定為 "System.Data.SqlClient"。如果您使用 Oracle 資料庫,請將 ProviderName 屬性設定為 "System.Data.OracleClient" 等。

  • ConnectionString 設定為資料庫使用的連接字串。

  • SelectCommand 設定為從資料庫傳回資料的 SQL 查詢或預存程序。為 SelectCommand 屬性設定的查詢,與您在撰寫 ADO.NET 資料存取程式碼時,為 ADO.NET IDbCommand 物件之 CommandText 屬性設定的查詢相同。SQL 查詢的實際語法要視資料的結構描述和您所使用的資料庫而定。

下列小節詳細描述了這些屬性。

指定提供者名稱

ProviderName 屬性設定為與儲存資料之資料庫類型關聯的 ADO.NET 提供者名稱。允許的提供者清單會註冊在組態檔 (Machine.config 或 Web.config 檔) 的 DbProviderFactories 區段中。根據預設,SqlDataSource 控制項會使用對應至 Microsoft SQL Server 的 System.Data.SqlClient ADO.NET 提供者。因此如果您連接至 SQL Server 資料庫,就不需要明確指定提供者。然而,您也可以指定 System.Data.OracleClientSystem.Data.OdbcSystem.Data.OleDb 提供者。如需詳細資訊,請參閱 ADO.NET

注意事項:

請勿將 ProviderName 屬性設定為 Unmanaged ADO 提供者的值,例如 SQLOLEDB 或 MSDAORA。

指定連接字串

ConnectionString 屬性設定為特定資料庫使用的連接字串。然而,將 SqlDataSource 控制項的 ConnectionString 屬性設定為特定連接字串,在大型站台中不是非常容易管理的策略。此外,連接字串就會以純文字儲存在 ASP.NET 網頁中。若要讓 Web 應用程式更容易管理且更加安全,建議您將連接字串儲存在應用程式組態檔的 connectionStrings 項目中。然後就能夠使用像是下列範例中的連接運算式,參考儲存的連接字串:

<asp:SqlDataSource 
  ID="SqlDataSource1" 
   
  ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
   SelectCommand="SELECT * FROM [Categories]">
</asp:SqlDataSource>

如需更高的安全性,可以加密 <connectionStrings> 組態區段的內容。如需詳細資訊,請參閱加密和解密組態區段

指定選取命令

您可以藉由設定 SqlDataSource 控制項的 SelectCommand 屬性,指定要執行的 SQL 查詢。下列範例說明,擷取由 Employees 資料表中所有員工姓氏所組成之結果集的 SQL 查詢:

SELECT LastName FROM Employees;

下列程式碼範例會示範如何將 SqlDataSource 控制項的 ConnectionStringSelectCommand 屬性,設定為在 GridView 控制項中顯示員工資料:

<%@ Page language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head >
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" >
      <asp:SqlDataSource
          id="SqlDataSource1"
          
          DataSourceMode="DataReader"
          ConnectionString="<%$ ConnectionStrings:MyNorthwind%>"
          SelectCommand="SELECT LastName FROM Employees">
      </asp:SqlDataSource>

      <asp:ListBox
          id="ListBox1"
          
          DataTextField="LastName"
          DataSourceID="SqlDataSource1">
      </asp:ListBox>

    </form>
  </body>
</html>
<%@ Page language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head >
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" >
      <asp:SqlDataSource
          id="SqlDataSource1"
          
          DataSourceMode="DataReader"
          ConnectionString="<%$ ConnectionStrings:MyNorthwind%>"
          SelectCommand="SELECT LastName FROM Employees">
      </asp:SqlDataSource>

      <asp:ListBox
          id="ListBox1"
          
          DataTextField="LastName"
          DataSourceID="SqlDataSource1">
      </asp:ListBox>

    </form>
  </body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head >
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" >
      <asp:SqlDataSource
          id="SqlDataSource1"
          
          DataSourceMode="DataReader"
          ConnectionString="Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;"
          SelectCommand="SELECT LastName FROM Employees">
      </asp:SqlDataSource>

      <asp:ListBox
          id="ListBox1"
          
          DataTextField="LastName"
          DataSourceID="SqlDataSource1">
      </asp:ListBox>

    </form>
  </body>
</html>

如果您使用的資料庫支援預存程序,可以將 SelectCommand 屬性設定為預存程序的名稱,並且設定 SelectCommandType 屬性 StoredProcedure 表示 SelectCommand 屬性參考預存程序。下列範例說明可以在 SQL Server 中建立的簡單預存程序:

CREATE PROCEDURE sp_GetAllEmployees AS
    SELECT * FROM Employees;
GO

若要將 SqlDataSource 設定為使用這個預存程序,請將 SelectCommand 文字設定為 "sp_GetAllEmployees" 以及將 SelectCommandType 屬性設定為 StoredProcedure

大部分的預存程序都會使用參數。如需搭配參數使用預存程序的詳細資訊,請參閱使用參數和 SqlDataSource 控制項

在執行階段,SqlDataSource 控制項會將 SelectCommand 屬性中的文字送出至資料庫,然後資料庫會將查詢或預存程序結果傳回 SqlDataSource 控制項。繫結至資料來源控制項的任何 Web 控制項會在 ASP.NET 網頁上顯示結果集。

將參數傳遞至 SQL 陳述式

使用者通常會根據只能在執行階段解析或評估的參數與資料進行互動。例如,ASP.NET 網頁上顯示的資料可能代表特定日期的報表。如果使用者選取不同的日期,報表中的資料可能也會變更。不論是使用者明確變更日期,或是 Web 應用程式以程式設計方式變更日期,如果您送出至資料庫的 SQL 查詢是參數型的 SQL 查詢 (SQL 陳述式的項目會繫結至 Web 應用程式變數,並且在執行階段進行評估),就可以更有彈性並且更容易維護。

SqlDataSource 控制項會藉由使您加入至 SelectParameters 集合的參數,與 SelectCommand 查詢中的替代符號 (Placeholder) 產生關聯,以支援參數化 SQL 查詢。您可以從網頁上的其他控制項、工作階段狀態、使用者設定檔和其他項目讀取參數值。如需詳細資訊,請參閱使用參數和 SqlDataSource 控制項

預留位置使用的語法會依照資料庫類型而有所不同。如果您使用 SQL Server,參數名稱的開頭是 '@' 字元,並且它的名稱會對應至 SelectParameters 集合中的 Parameter 物件名稱。如果您使用 ODBC 或 OLE DB 資料庫,就不會命名參數型陳述式中的參數,而是使用預留位置字元 '?' 來指定。

下列範例說明參數型 SQL 查詢如何根據目前登入員工的 ID,擷取 SQL Server Northwind 資料庫中的所有訂單。

SELECT * FROM Orders WHERE EmployeeID = @empid

在這個範例中,@empid 運算式是在執行階段評估的參數。

下列程式碼範例說明從網頁的其他控制項取得參數值的參數型 SQL 查詢:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head >
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" >

      <p><asp:dropdownlist
          id="DropDownList1"
          
          autopostback="True">
          <asp:listitem selected="True">Sales Representative</asp:listitem>
          <asp:listitem>Sales Manager</asp:listitem>
          <asp:listitem>Vice President, Sales</asp:listitem>
      </asp:dropdownlist></p>

      <asp:sqldatasource
          id="SqlDataSource1"
          
          connectionstring="<%$ ConnectionStrings:MyNorthwind%>"
          selectcommand="SELECT LastName FROM Employees WHERE Title = @Title">
          <selectparameters>
              <asp:controlparameter name="Title" controlid="DropDownList1" propertyname="SelectedValue"/>
          </selectparameters>
      </asp:sqldatasource>

      <p><asp:listbox
          id="ListBox1"
          
          datasourceid="SqlDataSource1"
          datatextfield="LastName">
      </asp:listbox></p>

    </form>
  </body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head >
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" >

      <p><asp:dropdownlist
          id="DropDownList1"
          
          autopostback="True">
          <asp:listitem selected="True">Sales Representative</asp:listitem>
          <asp:listitem>Sales Manager</asp:listitem>
          <asp:listitem>Vice President, Sales</asp:listitem>
      </asp:dropdownlist></p>

      <asp:sqldatasource
          id="SqlDataSource1"
          
          connectionstring="<%$ ConnectionStrings:MyNorthwind%>"
          selectcommand="SELECT LastName FROM Employees WHERE Title = @Title">
          <selectparameters>
              <asp:controlparameter name="Title" controlid="DropDownList1" propertyname="SelectedValue"/>
          </selectparameters>
      </asp:sqldatasource>

      <p><asp:listbox
          id="ListBox1"
          
          datasourceid="SqlDataSource1"
          datatextfield="LastName">
      </asp:listbox></p>

    </form>
  </body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head >
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" >

      <p><asp:DropDownList
          id="DropDownList1"
          
          AutoPostBack="True">
          <asp:ListItem Selected="True">Sales Representative</asp:ListItem>
          <asp:ListItem>Sales Manager</asp:ListItem>
          <asp:ListItem>Vice President, Sales</asp:ListItem>
      </asp:DropDownList></p>

      <asp:SqlDataSource
          id="SqlDataSource1"
          
          ConnectionString="Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;"
          SelectCommand="SELECT LastName FROM Employees WHERE Title = @Title">
          <SelectParameters>
              <asp:ControlParameter Name="Title" ControlId="DropDownList1" PropertyName="SelectedValue"/>
          </SelectParameters>
      </asp:SqlDataSource>

      <p><asp:ListBox
          id="ListBox1"
          
          DataSourceID="SqlDataSource1"
          DataTextField="LastName">
      </asp:ListBox></p>

    </form>
  </body>
</html>

如需搭配 SqlDataSource 控制項使用參數的詳細資訊,請參閱使用參數和 SqlDataSource 控制項。如需使用資料來源參數的詳細資訊,請參閱使用含有資料來源控制項的參數

指定資料傳回的方式

SqlDataSource 控制項的 DataSourceMode 屬性會判斷 SqlDataSource 控制項維護資料的方式。根據預設,DataSourceMode 屬性是設定為 DataSet,表示資料庫傳回的結果集是藉由 SqlDataSource 控制項儲存在伺服器記憶體中。當 SqlDataSource 控制項在 DataSet 模式擷取資料時,關聯的資料繫結控制項,例如 GridViewDetailsView 可以提供豐富的資料顯示能力,例如自動排序和分頁。

此外,您也可以將 DataSourceMode 屬性設定為 DataReader,表示結果集並未儲存在記憶體中。在不需要將結果集保留在伺服器記憶體的案例中,請使用 DataReader 模式。

下列程式碼範例說明,在不需要排序、分頁或篩選的案例中,如何將 SqlDataSource 控制項的 DataSourceMode 屬性設定為 DataReader

<%@ Page language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head >
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" >
      <asp:SqlDataSource
          id="SqlDataSource1"
          
          DataSourceMode="DataReader"
          ConnectionString="<%$ ConnectionStrings:MyNorthwind%>"
          SelectCommand="SELECT LastName FROM Employees">
      </asp:SqlDataSource>

      <asp:ListBox
          id="ListBox1"
          
          DataTextField="LastName"
          DataSourceID="SqlDataSource1">
      </asp:ListBox>

    </form>
  </body>
</html>
<%@ Page language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head >
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" >
      <asp:SqlDataSource
          id="SqlDataSource1"
          
          DataSourceMode="DataReader"
          ConnectionString="<%$ ConnectionStrings:MyNorthwind%>"
          SelectCommand="SELECT LastName FROM Employees">
      </asp:SqlDataSource>

      <asp:ListBox
          id="ListBox1"
          
          DataTextField="LastName"
          DataSourceID="SqlDataSource1">
      </asp:ListBox>

    </form>
  </body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head >
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" >
      <asp:SqlDataSource
          id="SqlDataSource1"
          
          DataSourceMode="DataReader"
          ConnectionString="Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;"
          SelectCommand="SELECT LastName FROM Employees">
      </asp:SqlDataSource>

      <asp:ListBox
          id="ListBox1"
          
          DataTextField="LastName"
          DataSourceID="SqlDataSource1">
      </asp:ListBox>

    </form>
  </body>
</html>

使用 SqlDataSource 控制項事件加入自訂處理

SqlDataSource 控制項會公開您能夠處理的事件,以便在控制項執行資料擷取作業的前後執行自己的程式碼。

SqlDataSource 控制項在呼叫 Select 方法之前引發 Selecting 事件,以執行 SelectCommand 屬性中設定的 SQL 查詢。您可以處理 Selecting 事件以便在執行之前檢視 SQL 查詢,以及驗證 SelectParameters 集合中包含的參數,或是在擷取資料之前執行任何其他工作。例如,如果您搭配 SqlDataSource 控制項使用 FormParameter,可以處理 Selecting 事件以便在擷取資料前驗證參數的值 (FormParameter 會取得發佈在 HTML 項目中的值,並且在不經過任何驗證的情況下將它送出至資料庫)。如果值無法接受,您可以將 SqlDataSourceSelectingEventArgs 物件的 Cancel 屬性設定為 true 以取消查詢。

SqlDataSource 控制項在擷取資料後會引發 Selected 事件。您可以處理 Selected 事件判斷在資料庫作業期間是否擲回例外狀況,或是檢視資料作業傳回的任何值。

顯示資料

若要在 ASP.NET 網頁上顯示資料,您可以使用像是 GridViewDetailsViewFormView 的資料繫結控制項,或是例如 ListBoxDropDownList 的控制項。資料繫結控制項是做為 SqlDataSource 控制項所擷取資料的消費者。將資料繫結控制項的 DataSourceID 屬性設定為 SqlDataSource 控制項的 ID。當呈現網頁時,SqlDataSource 控制項會擷取資料並且讓資料繫結控制項使用,以便讓其顯示資料。如需資料繫結控制項,以及如何搭配資料來源控制項使用以顯示資料的詳細資訊,請參閱ASP.NET 資料繫結 Web 伺服器控制項概觀

下列程式碼範例說明如何使用 GridView 控制項顯示查詢結果。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head >
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" >

      <asp:SqlDataSource
          id="SqlDataSource1"
          
          DataSourceMode="DataReader"
          ConnectionString="<%$ ConnectionStrings:MyNorthwind%>"
          SelectCommand="SELECT FirstName, LastName, Title FROM Employees">
      </asp:SqlDataSource>

      <asp:GridView
          id="GridView1"
          
          DataSourceID="SqlDataSource1">
      </asp:GridView>

    </form>
  </body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head >
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" >

      <asp:SqlDataSource
          id="SqlDataSource1"
          
          DataSourceMode="DataReader"
          ConnectionString="<%$ ConnectionStrings:MyNorthwind%>"
          SelectCommand="SELECT FirstName, LastName, Title FROM Employees">
      </asp:SqlDataSource>

      <asp:GridView
          id="GridView1"
          
          DataSourceID="SqlDataSource1">
      </asp:GridView>

    </form>
  </body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head >
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" >

      <asp:SqlDataSource
          id="SqlDataSource1"
          
          DataSourceMode="DataReader"
          ConnectionString="Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;"
          SelectCommand="SELECT FirstName, LastName, Title FROM Employees">
      </asp:SqlDataSource>

      <asp:GridView
          id="GridView1"
          
          DataSourceID="SqlDataSource1">
      </asp:GridView>

    </form>
  </body>
</html>

請參閱

概念

SqlDataSource Web 伺服器控制項概觀