简体   繁体   English

SQLite3 Python-检查条目是否存在

[英]SQLite3 Python - Checking if an entry exists

I'm trying to check for duplicate usernames in a database but I'm getting the error: 我正在尝试检查数据库中是否有重复的用户名,但出现错误:

sqlite3.ProgrammingError: Incorrect number of bindings supplied. sqlite3.ProgrammingError:提供的绑定数量不正确。 The current statement uses 1, and there are 3 supplied. 当前语句使用1,并且提供了3。

What are the bindings referred to here and how might I go about fixing this? 这里提到的绑定是什么,我该如何解决?

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")

There's a subtle problem in this line: 这行有一个微妙的问题:

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

The second argument to .execute() must be a container! .execute()的第二个参数必须是容器!
So you can do something like this instead and it will work: 因此,您可以改为执行以下操作,它将起作用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM