c#之间的条件不起作用

时间:2014-02-16 08:04:12

标签: c# sql sql-server

   String start_cd;
   String end_cd;
   int time_start_int;
   int time_end_int;
    opencon();

     SqlCommand res = new SqlCommand("SELECT ID,Available,Type," + start_cd + "," + end_cd + " FROM " + going + " WHERE " + start_cd + "!=0 or " + end_cd + "!=0 and " + start_cd + " >= " + time_start_int + " and " + start_cd + " <= " + time_end_int + "", con);
    SqlDataAdapter sda_res = new SqlDataAdapter(res);
    DataTable dt_res = new DataTable();
    sda_res.Fill(dt_res);

    listBox1.DataSource=dt_res;
    listBox1.DisplayMember="ID";

    listBox2.DataSource = dt_res;
    listBox2.DisplayMember = start_cd;

我没有错误 但列表框显示未过滤的值(我希望在time_end_int之间设置值time_start_int)

3 个答案:

答案 0 :(得分:0)

您需要在{@ p>这样的单独表达式中将time_start_inttime_end_intstart_cd进行比较

SqlCommand res = new SqlCommand("SELECT ID,Available,Type," + start_cd + "," + 
    end_cd + " FROM " + going + 
   " WHERE " + start_cd + "!=0 or " + end_cd + "!=0 and " + 
   time_start_int + " <= " + start_cd + " and " +
   start_cd + " <= " + time_end_int + "", 
   con);

请记住,使用字符串连接SQL语句会使您的代码容易受到SQL注入攻击。您可以参考Algorithm to avoid SQL injection on MSSQL Server from C# code?获取有关如何避免SQL注入攻击的一些提示。

答案 1 :(得分:0)

首先我使用括号or,因为and将先计算,可能会导致删除所有过滤器,第二部分我会写time_start_int + " <= " + start_cd + " and " + start_cd + " <= " + time_end_int,因为我们需要start_cd在time_start_int和time_end_int之间:

SqlCommand res = new SqlCommand("SELECT ID,Available,Type," + start_cd + "," + 
    end_cd + " FROM " + going + 
   " WHERE (" + start_cd + "!=0 or " + end_cd + "!=0 ) and " + 
   time_start_int + " <= " + start_cd + " and " + start_cd + " <= " + time_end_int + "", con);

答案 2 :(得分:-1)

SqlCommand res = new SqlCommand("SELECT ID,Available,Type,"'+ start_cd +'","' +
        end_cd +'" FROM going  
       WHERE "'+ start_cd +'"!=0 or "'+ end_cd +'"!=0 and " + 
       time_start_int + " <= "'+ start_cd +'" <= " + time_end_int + "", con);

你错过了'(单引号)字符串变量。