Python SQLite 使用通配符的LIKE参数替换
我正在尝试使用Python的Sqlite库进行一个带参数的LIKE查询,代码如下:
self.cursor.execute("select string from stringtable where string like '%?%' and type = ?", (searchstr,type))
但是在通配符里面的?没有被正确处理,导致我出现了这个错误:
"sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 2 supplied."
我还尝试过用另一种方式查询,像这样:
like '%:searchstr%'
,并在列表中包含{"searchstr":searchstr...
但是这样做查询虽然能运行,但却从来没有返回任何结果,尽管我手动输入"like '%a%'"...
却能返回成百上千的结果,这本来是应该的。
有没有什么建议呢?
2 个回答
-1
虽然这不是对问题的确切回答,也不是想要竞争成为答案,但这个解决方案还是试图回应“在LIKE中进行参数替换”这个标题所引起的关注(就像我一样)。
我在做类似的事情时,将两种风格结合在了一起。这样,用户可以在函数中输入字段名,同时在搜索参数中包含“%”。
虽然字段名需要进行处理,但在小型测试项目中这样做是足够的。而且将“%”这个通配符从查询中移到参数中,允许用户使用其他的通配符。
database.py
def find_item(field,term):
cursor.execute("""
SELECT rowid,* FROM customers
WHERE (%s) LIKE ?
"""%field,(term,))
app.py
import database
database.find_item("first_name","%li%")
database.find_item("email","_li%")
111
引号的作用是让 ?
或 :name
不被当作占位符,而是被当作字面意思来处理。你需要在你传递的字符串周围加上百分号,并且使用没有引号的普通占位符。也就是说:
self.cursor.execute(
"select string from stringtable where string like ? and type = ?",
('%'+searchstr+'%', type))
注意,?
这个符号没有用引号包起来——这正是它们被当作占位符的正确方式。