rainbow-1
 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.

相关文章: