我在dict中的查询字符串用于过滤WHERE子句中的数据。
parameters =
{
"manufacuturerId": "1",
"fileName": "abc1234 ",
"categoryName": "normal"
}
SQL查询为:
fileSql = "select * from file_table as a
left join category_table as b
on a.fId = b.fId
left join manufacturer_table as c
on c.mId = a.mId
where c.manufacturerId = %(manufacturerId)s and
a.file_name = %(fileName)s and
b.name = %(categoryName)s ;"
cursor.execute(fileSql,(parameters))
使用参数化查询将dict的值基于键绑定到SQL查询时,效果很好。
但是,如果我的查询字符串更改为
,则这种方式并不灵活{
"manufacuturerId": "1",
"fileName": "abc1234 "
}
然后,代码将消失。
唯一的manufacuturerId是必须的,而其他键值对是可选的,以便进一步过滤。
如何优化代码?
答案 0 :(得分:1)
最简单的答案就是动态建立查询,即:
fileSql = """
select * from file_table as a
left join category_table as b on a.fId = b.fId
left join manufacturer_table as c on c.mId = a.mId
where c.manufacturerId = %(manufacturerId)s
"""
if "fileName" in parameters:
fileSql += " and a.file_name = %(fileName)s "
if "categoryName" in parameters:
fileSql += " and b.name = %(categoryName)s "
请注意,这仍然不是最佳选择,因为即使在不需要时,我们仍将连接保留在category_table
上。也可以通过动态构建“ from”子句以类似的方式解决,如果您的项目中只有几个这样的情况也可以-但大多数情况下,数据库驱动的应用程序需要大量动态查询并进行构建手工使用纯字符串很快会变得乏味且容易出错,因此您可能需要检查一下ORM(想到Peewee)能为您做什么。