Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在LIKE中使用通配符替换Python SQLite参数_Python_Sqlite_Sql Like - Fatal编程技术网

在LIKE中使用通配符替换Python SQLite参数

在LIKE中使用通配符替换Python SQLite参数,python,sqlite,sql-like,Python,Sqlite,Sql Like,我正在尝试使用Python的Sqlite库的参数化查询,如下所示: self.cursor.execute("select string from stringtable where string like '%?%' and type = ?", (searchstr,type)) 但是那是什么呢?未对通配符的内部进行求值,导致以下错误: "sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current

我正在尝试使用Python的Sqlite库的参数化查询,如下所示:

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."
我还尝试使用带标签的查询版本:

类似“%:searchstr%”
并且在列表中有
{“searchstr”:searchstr…

但是,当我这样做时,查询会运行,但不会返回任何结果,即使手动输入
“如“%a%”,…
会返回数百个结果


有什么建议吗?

引号保护
:name
不被用作占位符--它们是按字面意思取的。您需要在传递的字符串周围放置百分号,并使用不带引号的普通占位符。例如:

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

请注意,这两个
都不在引号中--这正是它们作为占位符应该做的。

虽然不是问题的确切答案,也不是竞争问题的答案,但是这个解决方案仍然试图回答“类似中的参数替换”,因为标题也考虑到了这一点(就像它对我一样)


我是以类似的方式工作的,我将两种样式组合在一起。这样,用户可以在搜索参数本身中输入字段名和“%”

虽然字段名需要卫生,但在小型测试项目中使用就足够了。同时,将“%”通配符从查询移动到参数允许用户使用其他通配符

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%")

@huntler,总是很乐意帮忙!Python有类似PHP的双引号变量解析吗?例如,
“$var”
在PHP中,将解析为括在引号中的
$var
值。@HammanSamuel,不,在Python中,单引号和双引号是等效的——要插入变量,必须是显式的,例如您可以使用,传递例如
vars()
.substitute
方法。哇,这太令人惊讶了!有没有办法绕过它?有没有办法将%放在de字符串中?顺便说一句,谢谢你的回答,它工作起来很有魅力