Error while extracting value from database aiosqlite python, ProgrammingError: Incorrect number of bindings supplied
Error while extracting value from database aiosqlite python, ProgrammingError: Incorrect number of bindings supplied
我正在 python 中使用 sqlite 作为数据库编写电报机器人。我使用 aiosqlite 作为连接数据库和执行值的框架。在数据库中我有 3 列,它看起来像:
user_id, user_name, balance
802123124,@toppythonguy,0
79124142124,@None,0
当我通过此函数使用 user_id 获得平衡时,它工作正常
async def tryer(userid, column="user_id"):
sql_connection = await aiosqlite.connect("users.db")
sql_cursor = await sql_connection.cursor()
await sql_cursor.execute(f'''SELECT balance FROM users WHERE {column} == {userid}''')
user_balance = await sql_cursor.fetchall()
await sql_connection.close()
if not user_balance:
return False
else:
return user_balance
但是当我使用用户名(例如:@Goodfella)尝试相同的代码时,出现错误:
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 0 supplied.
我已经尝试了一些来自 stackowerflow 的解决方案,但 none 对我有效
问题是您正在使用 f 字符串来构造 SQL 语句。当您尝试使用 user_name
时,您最终会得到
SELECT BALANCE FROM users WHERE user_name = @toppythonguy
SQLite 使用 @
(以及其他一些字符)来指示绑定参数,在本例中名为 toppythonguy
。它期待您在调用 execute
.
时提供值
将值用引号引起来应该会有所帮助。但是,它可能会破坏您的 user_id
查询,因为您将使用字符串而不是整数。
真正的解决方法是始终使用绑定参数。
await sql_cursor.execute(f”SELECT balance FROM users WHERE {column} = ?”, userid)
作为一般经验法则,您不希望允许用户提供的值进入您构建的 SQL 查询。使用您的原始查询,想象一下如果有人将此作为他们的用户名提交
1; DELETE FROM users
绑定参数是避免这种情况的方法。根据 column
的填充方式,您可能也需要在那里做一些事情,但只要调用 tryer
的代码从预定列表中选择它就可以了。
我正在 python 中使用 sqlite 作为数据库编写电报机器人。我使用 aiosqlite 作为连接数据库和执行值的框架。在数据库中我有 3 列,它看起来像:
user_id, user_name, balance
802123124,@toppythonguy,0
79124142124,@None,0
当我通过此函数使用 user_id 获得平衡时,它工作正常
async def tryer(userid, column="user_id"):
sql_connection = await aiosqlite.connect("users.db")
sql_cursor = await sql_connection.cursor()
await sql_cursor.execute(f'''SELECT balance FROM users WHERE {column} == {userid}''')
user_balance = await sql_cursor.fetchall()
await sql_connection.close()
if not user_balance:
return False
else:
return user_balance
但是当我使用用户名(例如:@Goodfella)尝试相同的代码时,出现错误:
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 0 supplied.
我已经尝试了一些来自 stackowerflow 的解决方案,但 none 对我有效
问题是您正在使用 f 字符串来构造 SQL 语句。当您尝试使用 user_name
时,您最终会得到
SELECT BALANCE FROM users WHERE user_name = @toppythonguy
SQLite 使用 @
(以及其他一些字符)来指示绑定参数,在本例中名为 toppythonguy
。它期待您在调用 execute
.
将值用引号引起来应该会有所帮助。但是,它可能会破坏您的 user_id
查询,因为您将使用字符串而不是整数。
真正的解决方法是始终使用绑定参数。
await sql_cursor.execute(f”SELECT balance FROM users WHERE {column} = ?”, userid)
作为一般经验法则,您不希望允许用户提供的值进入您构建的 SQL 查询。使用您的原始查询,想象一下如果有人将此作为他们的用户名提交
1; DELETE FROM users
绑定参数是避免这种情况的方法。根据 column
的填充方式,您可能也需要在那里做一些事情,但只要调用 tryer
的代码从预定列表中选择它就可以了。