如果想要搜索包含单词" hex"和"坚果"我会使用这样的查询:
cursor.execute("SELECT description FROM %s WHERE description LIKE %?% AND
description LIKE %?%" % table_name , ["hex", "nut" ])
但是如果用户现在想要搜索包含5个术语的描述呢?
以前在纯sql中我写了这样的东西来生成我的结果:
base = """
SELECT description FROM {0}
WHERE
""".format(table_name)
command = base
# Adding "AND" for each term
for i in range(len(search_terms)):
# Last portion of the SQL query
if i == (len(search_terms) - 1):
command += " description LIKE '%{0}%'".format(search_terms[i])
else:
command += " description LIKE '%{0}%' AND ".format(search_terms[i])
command = command.replace("\n", "")
cursor.execute(command)
但是我希望有更好的方法来使用sqlite和sql查询。我知道我可以将所有数据加载到内存中并使用纯Python来实现我想要的但我想要SQL。这样做有一种优雅而安全的方式吗?
我是stackoverflow和SQL的新手,所以如果我的问题错了,请告诉我。
答案 0 :(得分:0)
考虑使用Pythons的str.join
列表理解:
table_name = 'prices' # EXAMPLE
command = """ SELECT description FROM {0} WHERE """.format(table_name)
search_terms = ['hex', 'nut', 'screw', 'bolt', 'nail'] # EXAMPLE
where = ' AND '.join(["description LIKE '%?%'" for i in search_terms])
command = command + where
print(command)
# SELECT description FROM prices WHERE description LIKE %?% AND description LIKE %?%
# AND description LIKE %?% AND description LIKE %?% AND description LIKE %?%
cursor.execute(command, search_terms) # PARAMETERIZED QUERY