简体   繁体   English

在SQL查询的aspx页面中使用会话变量

[英]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. 我在aspx页面中有sqldatasource,在查询中我想使用一个参数,即来自会话。

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. 这篇MSDN文章应该为您提供所需的信息。 Basically you would define your SelectCommand with the parameter placeholder, "?", and then define your SelectParameters collection with an entry for your SessionParameter. 基本上,您将使用参数占位符“?”定义SelectCommand,然后使用SessionParameter的条目定义SelectParameters集合。

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: Johnny_D的答案很明确,但是我想指出,有一个SessionParameter类可用于此目的:

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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