【问题标题】:c# between in where condition not work [duplicate]c# between where条件不起作用[重复]
【发布时间】:2014-02-16 08:04:11
【问题描述】:
   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 )

【问题讨论】:

  • 人们已经在您之前的问题中告诉过您,您将字符串连接起来创建查询是过时且有风险的。
  • 即使您坚持编写有 SQL 注入问题的代码,请花时间编辑您的示例,这样就不需要滚动(滚动浏览您的示例以尝试猜测错误是不必要的困难) .

标签: c# sql sql-server


【解决方案1】:

您需要在单独的表达式中将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 注入攻击的提示。

【讨论】:

    【解决方案2】:

    首先我为or 使用括号,因为and 将首先计算并且可能会导致删除所有过滤器,在第二部分我写time_start_int + " &lt;= " + start_cd + " and " + start_cd + " &lt;= " + 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);
    

    【讨论】:

    • +0:虽然可能是正确的,但没有解释你做了什么,更重要的是为什么。
    • 我收到错误“FOT”附近的语法错误。(FOT=start_cd)
    • 我希望这些变化能给你一些关于我做什么的线索。
    【解决方案3】:
    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);
    

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

    【讨论】:

      猜你喜欢
      • 2012-04-14
      • 2022-01-04
      • 2023-03-27
      • 2013-08-30
      • 2013-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多