SQLite3 Python - 检查条目是否存在

标签 sql database python-3.x sqlite

我正在尝试检查数据库中的重复用户名,但出现错误:

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

这里提到的绑定(bind)是什么?我该如何解决这个问题?

conn = sqlite3.connect('data.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS users (username, f_name, l_name, age, email, uid)''')
for u in range(0,1):
   a1 = input("Enter desired username:\t")
   a2 = input("Enter first name:\t")
   a3 = input("Enter last name:\t")
   a4 = input("Enter age:\t")
   a5 = input("Enter email:\t")
   a6 = str(uuid4())
   add = [a1,a2,a3,a4,a5,a6]
   c.execute('''SELECT username FROM users WHERE username=?''', a1)
   exists = c.fetchall()
   if not exists:
       c.execute('INSERT INTO users VALUES(?,?,?,?,?,?)',add)
       conn.commit()
   else:
       print("Error: Username already in use.\n")

最佳答案

这一行有一个微妙的问题:

c.execute('''SELECT username FROM users WHERE username=?''', a1)

.execute() 的第二个参数必须是一个容器!
所以你可以做这样的事情,它会起作用:

c.execute('''SELECT username FROM users WHERE username=?''', (a1,))
                                                           # ^  ^^ this is now a tuple!

关于SQLite3 Python - 检查条目是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47209849/

相关文章:

sql - PostgreSQL 中的递归

c# - 在 WPF 应用程序中连接和使用 SQL Compact Edition

python-3.x - 使用 Pandas 在同一图中绘制不同 DataFrame 的不同列

python - 如何在 Python 中翻转两点之间的曲线,并将凸曲线转换为凹曲线?

python - 如何在 Python 3.7 中向 multiprocessing.connection.Client(..) 添加超时?

mysql - 计算每个类别组的余额

sql - 根据计算值创建索引

database - Blackberry 的 SQlite 数据库有其他选择吗?

sql - 获取日期时间范围之间的类可用时间

mysql - 无法通过 PHPmyAdmin 导入 Wordpress 数据库 - 无法通过插件执行迁移