gpt4 book ai didi

python - SQLite 参数替换问题

转载 作者:IT老高 更新时间:2023-10-28 20:24:16 26 4
gpt4 key购买 nike

在 Python 2.5 中使用 SQLite3,我正在尝试遍历列表并根据项目名称从数据库中提取项目的权重。

我尝试使用“?”建议使用参数替换来防止 SQL 注入(inject),但它不起作用。例如,当我使用:

for item in self.inventory_names:
self.cursor.execute("SELECT weight FROM Equipment WHERE name = ?", item)
self.cursor.close()

我得到错误:

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

我相信这在某种程度上是由数据库的初始创建引起的;我创建的实际创建数据库的模块确实有 8 个绑定(bind)。

cursor.execute("""CREATE TABLE Equipment 
(id INTEGER PRIMARY KEY,
name TEXT,
price INTEGER,
weight REAL,
info TEXT,
ammo_cap INTEGER,
availability_west TEXT,
availability_east TEXT)""")

但是,当我对每个项目名称使用不太安全的“%s”替换时,它工作得很好。像这样:

for item in self.inventory_names:
self.cursor.execute("SELECT weight FROM Equipment WHERE name = '%s'" % item)
self.cursor.close()

我不明白为什么当我只调用一个时它认为我有 8 个绑定(bind)。我该如何解决?

最佳答案

Cursor.execute() 方法需要一个序列作为第二个参数。您提供的字符串恰好是 8 个字符长。

请改用以下表格:

self.cursor.execute("SELECT weight FROM Equipment WHERE name = ?", [item])

Python 库引用:sqlite3 Cursor Objects .

关于python - SQLite 参数替换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/228912/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com