简体   繁体   中英

using session variable in aspx page in sql query

I have the sqldatasource in aspx page and in the query I want to use one parameter ie coming from session.

Below is my code.Please help me out.

<asp:SqlDataSource runat="server" ID="MySQLData2"
ConnectionString='<%$ConnectionStrings:ConnectionString %>'
ProviderName="MySql.Data.MySqlClient"
SelectCommand="SELECT * FROM tablename  WHERE id="Here I want to use session variable"" />

Try this

<asp:SqlDataSource runat="server" ID="MySQLData2"
    ConnectionString='<%$ConnectionStrings:ConnectionString %>'
    ProviderName="MySql.Data.MySqlClient"
    SelectCommand="SELECT * FROM tablename  WHERE id=@SessionVar">
  <SelectParameters>
     <asp:SessionParameter Name="SessionVar" SessionField="SessionVariableName" ConvertEmptyStringToNull="true" />
  </SelectParameters>
</asp:SqlDataSource>

This MSDN article should get you what you need. Basically you would define your SelectCommand with the parameter placeholder, "?", and then define your SelectParameters collection with an entry for your SessionParameter.

Using parameters is rather simple:

 <asp:SqlDataSource id="Employees" runat="server"
  ConnectionString="<%$ ConnectionStrings:Northwind%>"
  SelectCommand="SELECT LastName FROM Employees WHERE Title = @Title">
  <SelectParameters>
    <asp:ControlParameter Name="Title" 
      ControlID="DropDownList1"
      PropertyName="SelectedValue"/>
  </SelectParameters>
</asp:sqldatasource>

Just replace the value of parameter with your variable:

 <%= Sessiom[variable_name] %>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="Data Source=LAZY-PC;Initial Catalog=Test;Integrated Security=True"
        ProviderName="System.Data.SqlClient" SelectCommand="SELECT * FROM [C] WHERE ([C#] = @column1)">
        <SelectParameters>
            <asp:SessionParameter Name="column1" SessionField="id" Type="String" />
        </SelectParameters>
    </asp:SqlDataSource>

Johnny_D's answer is pretty much spot on, but I'd like to point out that there's a SessionParameter class that you can use for this:

<asp:SqlDataSource runat="server" ID="MySQLData2"
    ConnectionString='<%$ConnectionStrings:ConnectionString %>'
    ProviderName="MySql.Data.MySqlClient"
    SelectCommand="SELECT * FROM tablename WHERE id= ?" />
      <SelectParameters>
          <asp:SessionParameter
            Name="id"
            SessionField="SessionVariableName"
            DefaultValue="0" />
      </SelectParameters>
  </asp:SqlDataSource>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM