如何在sqlite3-python命令中使用变量



我知道这看起来很基本,但无论我能找到什么答案都不适合我。

import sqlite3
conn = sqlite3.connect("mydb.db")

cursor = conn.cursor()

name = "John Doe"
cursor.execute("SELECT * FROM users WHERE username = ?", name)
items = cursor.fetchall()
print(items)

conn.close()

我试图获得用户名为"John Doe"的所有用户的列表(我知道有一个(,但之前的代码给出了以下错误:

Traceback (most recent call last):
File ".sqlitetest.py", line 10, in <module>
cursor.execute("SELECT * FROM users WHERE username = ?", name)
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 8 supplied.

变量应该在元组中传递,即使只传递了一个变量,即(name,(

cursor.execute("SELECT * FROM users WHERE username = ?", (name,))

通常我使用sql server作为数据库,我传递变量数据,如

query=f";从用户名为"{var_name}"的用户中选择*;

或query=";从用户名为"{}"的用户中选择*;。format(var_name(

最新更新