日期:2014-05-18  浏览次数:20515 次

Where语句怎么加入Session变量进行查询?
例如:
Session["kind"]=”地域”
Session["content"]=”大陆”

接收页面:
string ss = Session["kind"].ToString();
string sss = Session["content"].ToString();

sda.SelectCommand = new SqlCommand("select * from 影视档案表 where 地域 = '" + sss + "'");
能够正确查出信息,
但sda.SelectCommand = new SqlCommand("select * from 影视档案表 where '" + ss + "'= '" + sss + "'");

就不行。。。请问大侠怎么办啊??
我想用第二句查询,因为ss接受的Session的值不同,别的页面将Session的值传过来,在这个页面进行查询,其中Session的值都是影视档案表中的字段名。

注:插入断点检测,ss显示地域,sss显示大陆,但就是查不出结果。

全部代码:做的一个bind(),为GridView翻页使。
private void Bind()
  {
  SqlConnection con = DB.createConnection();
  SqlDataAdapter sda = new SqlDataAdapter();
  string ss = Session["kind"].ToString();
  string sss = Session["content"].ToString();
  sda.SelectCommand = new SqlCommand("select * from '" + ss + "' where 地域 = '" + sss + "'");
  DataSet ds = new DataSet();
  sda.SelectCommand.Connection = con;
  sda.Fill(ds, "影视档案表");
  GridView1.DataKeyNames = new string[] { "电影中文名" };
  this.GridView1.DataSource = ds.Tables["影视档案表"];
  this.GridView1.DataBind();
  }


------解决方案--------------------
where后面是字段名=值。。
这样写就行:
sda.SelectCommand = new SqlCommand("select * from " + ss + " where 地域 = '" + sss + "'");
------解决方案--------------------
C# code
sda.SelectCommand = new SqlCommand("select * from 影视档案表 where " + ss + "= '" + sss + "'");

------解决方案--------------------
sda.SelectCommand = new SqlCommand("select * from 影视档案表 where '" + ss + "'= '" + sss + "'"); 
----->
sda.SelectCommand = new SqlCommand("select * from 影视档案表 where " + ss + " = '" + sss + "'"); 

------解决方案--------------------
字段名是不需要加單引號的,所以去掉單引號及行了
sda.SelectCommand = new SqlCommand("select * from 影视档案表 where " + ss + "= '" + sss + "'"); 

------解决方案--------------------

这个问题应该是解决了,但不推荐 这么写。

看看这 个帖 http://topic.csdn.net/u/20080529/09/44F8A53B-5EA6-4412-8BB6-730889523C7E.html ,孟子推荐的。
------解决方案--------------------
探讨
字段名是不需要加單引號的,所以去掉單引號及行了
sda.SelectCommand = new SqlCommand("select * from 影视档案表 where " + ss + "= '" + sss + "'");