【问题标题】:SQLite3 Python - Checking if an entry existsSQLite3 Python - 检查条目是否存在
【发布时间】:2018-04-22 22:03:58
【问题描述】:

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

sqlite3.ProgrammingError:提供的绑定数量不正确。当前语句使用 1,提供了 3 个。

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

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

【问题讨论】:

    标签: sql database python-3.x sqlite


    【解决方案1】:

    这行有个微妙的问题:

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

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

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

    【讨论】:

    • 做到了。谢谢。
    猜你喜欢
    • 2013-09-19
    • 1970-01-01
    • 2015-07-14
    • 1970-01-01
    • 2012-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多