SqlDataSource 直接操作關聯式資料庫,適合中小型專案或快速原型。本教程介紹基本用法並與 ObjectDataSource 比較架構差異。
ConnectionString:資料庫連線字串 (支援 SQL Server、Oracle、MySQL、Access 等所有 ADO.NET Provider)。SelectCommand:SELECT 陳述式或預存程序名稱。SelectCommandType:Text (預設) / StoredProcedure。DataSourceMode:DataSet (預設,適合分頁/排序) / DataReader (唯讀、順向、低記憶體)。<asp:SqlDataSource ID="ProductsDS" runat="server"
ConnectionString="%$ ConnectionStrings:Northwind %$"
SelectCommand="SELECT ProductID, ProductName, UnitPrice FROM Products ORDER BY ProductName"
DataSourceMode="DataSet">
</asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" DataSourceID="ProductsDS" AllowPaging="True" AllowSorting="True" />
| 面向 | ObjectDataSource | SqlDataSource |
|---|---|---|
| 資料來源 | 自訂類別 (BLL/DAL) | 關聯式資料庫 (ADO.NET) |
| 查詢邏輯位置 | 類別方法 (C#/VB) | SQL 陳述式 / SP |
| 參數對應 | 方法參數 | SQL 參數 (@名稱) |
| 型別安全 | 編譯期強型別 | 執行期驗證 |
| 測試性 | 易於單元測試 | 需資料庫整合測試 |
| 適用專案 | 分層架構、中大型專案 | 快速開發、小型專案、報表 |