2010-06-23 117 views
27

我试图使用参数化查询功能有如下Python的SQLite库:的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%'"...返回数百结果,因为它应该

任何建议吗?

回答

53

引号保护?:name不被视为占位符 - 从字面上理解它们。您需要在您传递的字符串周围放置百分号,并使用不带引号的简单占位符。即:

self.cursor.execute(
    "select string from stringtable where string like ? and type = ?", 
    ('%'+searchstr+'%', type)) 

注意,无论?是在引号 - 而这正是因为它应该是为他们被视为占位符。

+0

非常感谢你!修复它! – atcuno 2010-06-23 21:04:37

+0

@ huntler,总是乐于帮忙! – 2010-06-23 21:06:30

+0

Python是否具有像PHP一样的双引号变量解析?例如在PHP中''$ var“'将解析为''var''的值,用引号引起来。 – 2015-06-18 21:39:59