首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 2.0 資料教程 48:SqlDataSource 參數化查詢完整指南

     編輯:關於ASP.NET

參數化查詢可防止 SQL Injection、提升計畫重用。本教程涵蓋宣告式與程式化兩種參數指定方式。

參數來源類型

宣告式範例:依查詢字串篩選產品

<asp:SqlDataSource ID="ProductsDS" runat="server"
    ConnectionString="%$ ConnectionStrings:Northwind %$"
    SelectCommand="SELECT ProductID, ProductName, UnitPrice FROM Products WHERE CategoryID = @CategoryID">
    <SelectParameters>
        <asp:QueryStringParameter Name="CategoryID" QueryStringField="cat" Type="Int32" DefaultValue="1" />
    </SelectParameters>
</asp:SqlDataSource>

程式化指定參數:Selecting 事件

protected void ProductsDS_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
    // 依據複雜商務邏輯動態決定參數
    if (User.IsInRole("Admin"))
        e.Command.Parameters["@CategoryID"].Value = DBNull.Value; // 全部分類
    else
        e.Command.Parameters["@CategoryID"].Value = GetUserDefaultCategory();
}

多參數組合查詢範例

SelectCommand="SELECT * FROM Products WHERE 
    (@CategoryID IS NULL OR CategoryID = @CategoryID) AND
    (@MinPrice IS NULL OR UnitPrice >= @MinPrice) AND
    (@MaxPrice IS NULL OR UnitPrice <= @MaxPrice)"

<SelectParameters>
    <asp:QueryStringParameter Name="CategoryID" QueryStringField="cat" Type="Int32" ConvertEmptyStringToNull="true" />
    <asp:ControlParameter Name="MinPrice" ControlID="txtMin" PropertyName="Text" Type="Decimal" ConvertEmptyStringToNull="true" />
    <asp:ControlParameter Name="MaxPrice" ControlID="txtMax" PropertyName="Text" Type="Decimal" ConvertEmptyStringToNull="true" />
</SelectParameters>

關鍵屬性:ConvertEmptyStringToNull

設為 true 時,空字串自動轉為 NULL,搭配 `IS NULL` 判斷可實現「未輸入即不篩選」效果。

儲存程序參數

同樣支援參數化,參數名稱需與 SP 定義一致 (含 @ 前綴),方向可設 Input/Output/ReturnValue。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
參數類型來源範例
QueryStringParameterURL 查詢字串<asp:QueryStringParameter Name="CategoryID" QueryStringField="cat" Type="Int32" />
ControlParameter頁面控制項屬性<asp:ControlParameter Name="Price" ControlID="txtPrice" PropertyName="Text" Type="Decimal" />
SessionParameterSession 變數<asp:SessionParameter Name="UserID" SessionName="UID" Type="Int32" />
ProfileParameter使用者設定檔<asp:ProfileParameter Name="Theme" PropertyName="Theme" Type="String" />
CookieParameterCookie 值<asp:CookieParameter Name="Lang" CookieName="Culture" Type="String" />
Parameter程式碼手動指定在 Selecting 事件中 e.Command.Parameters["@Price"].Value = 100;