美文网首页
动态拼接SQL语句

动态拼接SQL语句

作者: whenitsallover | 来源:发表于2018-08-13 17:47 被阅读0次

    where 1=1; 这个条件始终为True,在不定数量查询条件情况下,1=1可以很方便的规范语句。

    举个例子,如果做查询页面,并且,可查询的选项有多个,同时,还让用户自行选择并输入查询关键词,那么,按平时的查询语句的动态构造,就要有多个if进行判断用户的输入

    date_sql = " " if date == u'' else (" and field1='" + date + "' ")
    script_sql = " " if xxx== u'' else (" and field2 like'" + '%'+xxx+'%' "' ")
    sql = 'select  field_name from table_name  where 1=1' + date_sql + script_sql 
    

    where 1=1 恒成立,因此如果用户在多条件查询页面中,不选择任何字段、不输入任何关键词,那么,必将返回表中所有数据;如果用户在页面中,选择了部分字段并且输入了部分查询关键词,那么,就按用户设置的条件进行查询。

    if sTime != None and eTime != None and len(sTime) > 0 and len(eTime) > 0:
         sql_condition = " and date between '" + sTime + "' and '" + eTime + "'"
     elif sTime != None and len(sTime) > 0:
              sql_condition = " and date >= '" + sTime + "'"
          elif eTime != None and len(eTime) > 0:
              sql_condition = " and date <= '" + eTime + "'"
    
    sql = "select  field_name where 1=1" + sql_condition
    

    where 1=1的应用,不是什么高级的应用,也不是所谓的智能化的构造,仅仅只是为了满足多条件查询页面中不确定的各种因素而采用的一种构造一条正确能运行的动态SQL语句的一种方法。

    相关文章

      网友评论

          本文标题:动态拼接SQL语句

          本文链接:https://www.haomeiwen.com/subject/drbubftx.html