【发布时间】:2016-11-19 14:29:05
【问题描述】:
如果要搜索包含单词“hex”和“nut”的描述,我会使用这样的查询:
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 的新手,所以如果我问错了问题,请告诉我。
【问题讨论】: