Dropdownbox.selectedvalue 传递给 sql 评论

Dropdownbox.selectedvalue passing to sql comment

string ddorder = DropDownList2.SelectedValue; // column
string ddtype = DropDownList3.SelectedValue; //asc or desc
String str1 = "Select * from table1 order by("+ddorder+"  "+ddtype+")";

//因为ddtype有错误,我哪里做错了?

SqlCommand cmd = new SqlCommand(str1, con);
con.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter da1 = new SqlDataAdapter();
da1.SelectCommand = cmd;
DataSet ds1 = new DataSet();
da1.Fill(ds1, DropDownList2.SelectedValue);
GridView2.DataSource = ds1;
GridView2.DataBind();
con.Close();

据我所知,您不需要在 order by 子句中使用 ()It's syntax() 没有任何用途。

例如;

order by id desc

可以,但是

order by (id desc)

不行。

顺便说一下,使用 using statement 自动处理你的 SqlConnectionSqlCommandSqlDataAdapter,而不是手动调用 Close 方法。

此外,SELECT 语句不需要 cmd.ExecuteNonQuery(); 部分。这是不必要的,因为它 只是 执行您的 select 查询。它不做或 return 什么。

还有一些事情;

  • 将您的 table1 更改为有意义的内容。
  • 不要使用 SELECT *It's quite bad.

删除"order by"子句中的括号:

String str1 = "Select * from table1 order by "+ddorder+" "+ddtype;

使用Dynamic Query:

在此处更改:

string ddorder = DropDownList2.SelectedValue; // column
string ddtype = DropDownList3.SelectedValue; //asc or desc
String str1 = "exec(Select * from table1 order by "+ddorder+"  "+ddtype+")";

SqlCommand cmd = new SqlCommand(str1, con);
con.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter da1 = new SqlDataAdapter();
da1.SelectCommand = cmd;
DataSet ds1 = new DataSet();
da1.Fill(ds1);
GridView2.DataSource = ds1;
GridView2.DataBind();
con.Close();