- def find_worldByName(c_name,continent):
- print(c_name)
- print(continent)
- sql = " SELECT * FROM world WHERE 1=1 "
- if(c_name!=None):
- sql=sql+"AND ( c_name LIKE '%"+c_name+"%' )"
- if(continent!=None):
- sql=sql+" AND ( continent LIKE '%"+continent+"%') "
- sql=sql+" AND dt=(SELECT dt FROM world order by dt desc limit 1) order by confirm desc "
-
- # "AND continent LIKE '%%%%%s%%%%'" # " order by dt desc " %(c_name,continent)
- # sql_temp = " SELECT * FROM world WHERE c_name LIKE '%"+c_name+"%' "
- res = query(sql)
- list= []
- for i in res:
- # print(i)
- list.append(i)
- return list;
背景:
页面的搜索框是有两个搜索条件,一个是国家,一个是大洲。
那么在数据库查询的时候就会出现问题,如果国家传的值是None那么使用AND连接的sql语句这个条件会被
整体判定为false,也就是另一个查询条件 “大洲 ”就会作废,为了防止参数出现这样的错误。需要在写sql语
句的时候对参数是否为空加一个判断条件,然后逐层添加sql语句。
思路:
首先使用开头的一个sql语句:
- sql = " SELECT * FROM world WHERE 1=1 "
之后逐层判定参数是否为空,再拼接sql语句:
- if(c_name!=None):
- sql=sql+"AND ( c_name LIKE '%"+c_name+"%' )"
- if(continent!=None):
- sql=sql+" AND ( continent LIKE '%"+continent+"%') "
- 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.
到此这篇关于Python使用sql语句对mysql数据库多条件模糊查询的思路详解的文章就介绍到这了,更多相关Python mysql多条件模糊查询内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!