我有5个复选框进行查询,可以随便选中那几个一起查询
但sql语句不知道怎么写???
string sql="select * from new where";
if(this.check1.checked==true)
{sql+="and a="+"this.txt1.text.trim()";}
else if(this.check2.checked==true)
{sql+="and b="+"this.txt2.text.trim()";}
else if(this.check3.checked==true)
{sql+="and c="+"this.txt3.text.trim()";} .....
好像这样也错了,到底怎么写好呢?如果一个一个判断的话,要写很多个,

解决方案 »

  1.   

    string sql="select * from new where 1=1";
    if (txt1.Text.Trim() != "")
    {
      sql += " And xxx=" + txt1.Text.Trim();
    }if (txt1.Text.Trim() != "")
    {
      sql += " And xxx=" + txt1.Text.Trim();
    }
    ...关键在于原来的句子有个1=1。比你原来的那个稍微简单点。只用if就可以。但是注意:强烈建议你不要这样生成查询语句!!这样会受到用户的sql注入攻击。
      

  2.   

    string sql="select * from new where 1=1";
    if (txt1.Text.Trim() != "")
    {
      sql += " And xxx=" + txt1.Text.Trim();
    }if (txt2.Text.Trim() != "")
    {
      sql += " And yyy=" + txt2.Text.Trim();
    }if (txt3.Text.Trim() != "")
    {
      sql += " And zzz=" + txt3.Text.Trim();
    }