sqlDataSource选择不适用于where子句

时间:2013-03-04 09:56:39

标签: asp.net ado.net sqldatasource

我将gridview绑定到sqldatasource.my问题是当我在select语句中使用sqldatasource而没有where子句时它工作正常,但是当我将它与where子句一起使用时,它在Query Builder中的工作正常并且返回记录但在运行时没有工作。 我使用Sql Profiler并看到查询没有运行当我使用where子句。我听说.NET阻止运行查询与where子句因为SQL注入但我不知道如何更正我的查询。 我的sqldatasource:

<asp:SqlDataSource ID="SqlDataSource2" runat="server" 
        ConnectionString="<%$ ConnectionStrings:chargeDBConnectionString %>"  SelectCommand="SELECT CARDNUMBER, VISITDATE, ACCNUMBER, ACTIONCODE FROM LOGTABLE WHERE (CARDNUMBER = @cardno OR @cardno IS NULL AND CARDNUMBER &lt;&gt; N'-' AND @ttype = 1 OR @ttype = 0) AND (VISITDATE &gt;= @fdate AND VISITDATE &lt;= @edate) AND (ACCNUMBER = @accno OR @accno IS NULL AND ACCNUMBER &lt;&gt; N'-' AND @ttype = 0 OR @ttype = 1) AND (ACTIONCODE = @actioncode OR @actioncode IS NULL)">
        <SelectParameters>
            <asp:FormParameter FormField="cardNo" Name="cardno" />
            <asp:ControlParameter ControlID="ddlType" Name="ttype" 
                PropertyName="SelectedValue" />
            <asp:FormParameter FormField="fromDate" Name="fdate" />
            <asp:FormParameter FormField="toDate" Name="edate" />
            <asp:FormParameter FormField="accNo" Name="accno" />
            <asp:ControlParameter ControlID="ddltransname" Name="actioncode" 
                PropertyName="SelectedValue" />
        </SelectParameters>
    </asp:SqlDataSource>

1 个答案:

答案 0 :(得分:2)

最可能的罪魁祸首是你的一个参数正在评估为null,而SqlDataSource正在取消选择查询。

要更正这一点,您需要在SqlDataSource声明中将SqlDataSource.CancelSelectOnNullParameter属性设置为false(默认情况下为true):

<asp:SqlDataSource ID="SqlDataSource2" runat="server" 
    ConnectionString="<%$ ConnectionStrings:chargeDBConnectionString %>"  
    SelectCommand="SELECT CARDNUMBER, VISITDATE, ACCNUMBER, ACTIONCODE FROM LOGTABLE WHERE (CARDNUMBER = @cardno OR @cardno IS NULL AND CARDNUMBER &lt;&gt; N'-' AND @ttype = 1 OR @ttype = 0) AND (VISITDATE &gt;= @fdate AND VISITDATE &lt;= @edate) AND (ACCNUMBER = @accno OR @accno IS NULL AND ACCNUMBER &lt;&gt; N'-' AND @ttype = 0 OR @ttype = 1) AND (ACTIONCODE = @actioncode OR @actioncode IS NULL)"
    CancelSelectOnNullParameter="False">
    <SelectParameters>
        <asp:FormParameter FormField="cardNo" Name="cardno" />
        <asp:ControlParameter ControlID="ddlType" Name="ttype" 
            PropertyName="SelectedValue" />
        <asp:FormParameter FormField="fromDate" Name="fdate" />
        <asp:FormParameter FormField="toDate" Name="edate" />
        <asp:FormParameter FormField="accNo" Name="accno" />
        <asp:ControlParameter ControlID="ddltransname" Name="actioncode" 
            PropertyName="SelectedValue" />
    </SelectParameters>
</asp:SqlDataSource>