参数化 SQLite 查询的元组问题

问题描述 投票:0回答:1
我正在开发一个基于 telethon 的电报聊天机器人,它可以查询以以下格式给出姓氏的客户数据库:

/search thompson

,但在使用填充函数来保证查询安全时遇到一些问题:

list_of_words = event.message.text.split(" ") query = list_of_words[1] # get name here sql = "select exists(SELECT * from customers where lname = ?)" # I've tried two methods here, both using query directly: # args = query # and using join to convert the tuple to a string: args = ''.join((query)) cursor = conn.execute(sql, args) res = cursor.fetchall() # fetch all the results
但是,我遇到了两个错误之一 - 一个是直接访问 

tuple index out of range

 时的 
query
,以及使用 join(上面的方法 2)时的 
Incorrect number of bindings supplied. The current statement uses 1, and there are 8 supplied.
。我在这里做错了什么?

python tuples parameterization sqlite3-python
1个回答
0
投票

execute()

的第二个参数需要是值的
序列。即使您的查询只有一个参数,您仍然需要将其作为包含一个值的序列传递。

在您的代码中,您传递一个字符串作为第二个参数。从技术上讲,字符串

序列,但它将每个单独的字符解释为一个单独的项目,这就是为什么您会收到错误的绑定数量错误。

将第二个参数作为一项列表传递:

cursor = conn.execute(sql, [args])
或者作为一项的元组:

cursor = conn.execute(sql, (args,))
    
© www.soinside.com 2019 - 2024. All rights reserved.