应用场景:当sql 语句中where后面的条件字段为空的时候,条件不存在
eg:根据传入的参数,从student表中查询数据,参数包含姓名(name 必有),年龄(age 不一定有),性别(gender 不一定有)
思路1:
首先判断传入的参数都有哪几个,然后再去选择合适的sql语句
if name and age and gender:
sql = """ select * from student where name = '张三' and age=18 and gender= '男' """
elif name and age and not gender:
sql = """ select * from student where name = '张三' and age=18 """
elif name and not age and gender:
sql = """ select * from student where name = '张三' and gender= '男' """
elif name and not age and not gender:
sql = """ select * from student where name = '张三' """
思路二:
拼接利用字符串的特性,拼接sql语句
sql = """ select * from student where name = '张三' %s """ % 'and age=%s ' % age if age else ' ' + 'and gender = %s ' % gender if gender else ' '
当age 和gender都不存在时 sql语句就成了这样: select * from student where name = '张三'
大家可以试验一下,如有问题欢迎指正。