我有一个Python列表,即:
['E/123', 'E/145']
我想将此添加到我所做的SQL语句中:
WHERE GrantInformation.GrantRefNumber LIKE 'E/123'
OR GrantInformation.GrantRefNumber LIKE 'E/145'
我的代码是:
items = []
i = 0
while 1:
i += 1
item = input('Enter item %d: '%i)
if item == '':
break
items.append(item)
print(items)
refList = " OR GrantInformation.GrantRefNumber LIKE ".join(items)
问题是,当我将该String插入我的SQL时,它是一个String,因此它正在寻找WHERE GrantInformation.GrantRefNumber Like 'ES/P004355/1 OR GrantInformation.GrantRefNumber LIKE ES/P001452/1'
显然没有返回任何内容,因为'ES/P004355/1 OR GrantInformation.GrantRefNumber LIKE ES/P001452/1'
没有出现在字段中。
我如何做到' GrantInformation.GrantRefNumber LIKE '
不是字符串?
谢谢
答案 0 :(得分:1)
执行此操作的首选方法是使用SQLAlchemy之类的ORM 为你做查询构造,你不必自己制作字符串浓度。
join()
,在数组中的所有项之间添加字符串,作为参数传递。您还需要将条件添加到数组中:
>>> items = ['A', 'B']
>>> " OR ".join(["GrantInformation.GrantRefNumber LIKE '%s'" % num for num in items])
"GrantInformation.GrantRefNumber LIKE 'A' OR GrantInformation.GrantRefNumber LIKE 'B'"