zoukankan      html  css  js  c++  java
  • Python使用sql语句对mysql数据库多条件模糊查询

     1 def find_worldByName(c_name,continent):
     2     print(c_name)
     3     print(continent)
     4     sql = " SELECT * FROM world WHERE  1=1 "
     5     if(c_name!=None):
     6         sql=sql+"AND ( c_name LIKE '%"+c_name+"%' )"
     7     if(continent!=None):
     8         sql=sql+" AND ( continent LIKE '%"+continent+"%') "
     9     sql=sql+" AND dt=(SELECT dt FROM world order by dt desc limit 1) order by confirm desc "
    10 
    11           # "AND continent LIKE '%%%%%s%%%%'" 
    12           # " order by dt desc " %(c_name,continent)
    13     # sql_temp = " SELECT * FROM world WHERE c_name LIKE '%"+c_name+"%' "
    14     res = query(sql)
    15     list= []
    16     for i in res:
    17         # print(i)
    18         list.append(i)
    19     return list;

    背景:

    页面的搜索框是有两个搜索条件,一个是国家,一个是大洲。

    那么在数据库查询的时候就会出现问题,如果国家传的值是None那么使用AND连接的sql语句这个条件会被

    整体判定为false,也就是另一个查询条件 “大洲 ”就会作废,为了防止参数出现这样的错误。需要在写sql语

    句的时候对参数是否为空加一个判断条件,然后逐层添加sql语句。

    思路:

    首先使用开头的一个sql语句:

    sql = " SELECT * FROM world WHERE 1=1 "

    之后逐层判定参数是否为空,再拼接sql语句:

     5     if(c_name!=None):
     6         sql=sql+"AND ( c_name LIKE '%"+c_name+"%' )"
     7     if(continent!=None):
     8         sql=sql+" AND ( continent LIKE '%"+continent+"%') "
     9     sql=sql+" AND dt=(SELECT dt FROM world order by dt desc limit 1) order by confirm desc "
    

    还有一个地方需要注意:
    sql语句传参数,参数是一个变量,有两种方式:
    ① 直接拼接到sql语句中:
    var c_name="test"
    sql_temp = " SELECT * FROM world WHERE c_name LIKE ' %"+c_name+"% '"
    ② 使用占位符%代替,在语句末尾再替换占位符:
    sql = " SELECT * FROM world WHERE c_name LIKE '%%%%%s%%%%' AND continent LIKE '%%%%%s%%%%'" %(c_name,continent)

     Tomorrow the birds will sing.

  • 相关阅读:
    Hadoop 单机搭建 Scala安装
    Hadoop 单机搭建 Hbase单机模式搭建
    Hadoop 单机搭建 hadoop单机搭建
    Linux shell 重定向学习笔记
    转:SQLServer中的GROUPING,ROLLUP和CUBE
    ueditor getshell漏洞重现及分析
    SQLServer禁用、启用外键约束
    转:Sql Server中清空所有数据表中的记录
    EF结合SqlBulkCopy实现高效的批量数据插入 |EF插件EntityFramework.Extended实现批量更新和删除
    12种开源Web安全扫描程序
  • 原文地址:https://www.cnblogs.com/rainbow-1/p/14644126.html
Copyright © 2011-2022 走看看