Skip to main content
 首页 » 编程设计

python之为 SQLite3 和 Python 中的模式搜索形成经过清理的查询字符串

2025年05月04日2352php

我试图在 Python 中形成一个经过净化的查询字符串以在 SQLite3 中使用。它需要采用最终形式:

SELECT * FROM Players WHERE PlayerName LIKE '%bob%' 

...所以我可以运行模式搜索。

理想情况下我想要一个 ?在查询中,这样我就可以在运行查询时插入搜索字符串并防止 Bobby Tables 类型的事件发生(我不必担心那个 tbh):

search_string = "bob" 
 
query = "SELECT * FROM Players WHERE PlayerName LIKE '%?%'" 
 
cur.execute(query, (search_string)) 

运行这个给我:

sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 0, and there are 3 supplied.

所以我很确定问题出在单引号、百分号和问号的使用上,但我相当卡住——我无法形成查询,以便 python 认为它需要绑定(bind)。

解决这个问题的最佳方法是什么,或者是否有更好的做法来为 SQL 中的模式搜索形成经过清理的查询?

更新:最后一行是:

cur.execute(query, [('%' + search_string + '%')]) 

请您参考如下方法:

在LIKE 之后使用单独的占位符? 并在参数分配期间用% 包裹search_string:

... 
search_string = 'bob' 
query = 'SELECT * FROM Players WHERE PlayerName LIKE ?' 
cur.execute(query, ('%' + search_string + '%'))