简体   繁体   English

使用变量时出现Python SQLite3绑定错误

[英]Python SQLite3 Binding error when using variable

I have imported uuid and used it to randomly generate a 32 digit UserID, and at first it would work fine and register the user, but when I attempted to try and first check the database incase the UserID has already been used, I get a binding error, and can't figure out whats wrong with it. 我已经导入了uuid并使用它来随机生成一个32位用户ID,起初它可以正常工作并注册用户,但是当我尝试尝试并首先检查数据库时(如果已经使用了UserID的话),我得到了绑定错误,无法找出问题所在。

var_usertype = ("Teacher")
        Firstname = var_FName.get()
        Surname = var_SName.get()
        Password = var_password1.get()
        username = Firstname[0:3] + Surname
        conn = sqlite3.connect('MyComputerScience.db')
        c = conn.cursor()
        UserID = str(uuid.uuid4()).replace('-','')
        var_insert = (UserID, Firstname, Surname, Password, username, var_usertype)
        c.execute("SELECT * FROM users WHERE UserID = ?", (UserID))
        data = c.fetchall()
        if len(data) == 0:
            c.execute('insert INTO users (UserID, FName, SName, password, username, userType)VALUES(?,?,?,?,?,?);', var_insert)
            Label(screen2, text = "Successfully registered! Your username to log in is "+username+"", fg = "GREEN", font = "Calibri").pack()
            Main.login()



c.execute("SELECT * FROM users WHERE UserID = ?", (UserID))
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 32 supplied.
c.execute("SELECT * FROM users WHERE UserID = ?", (UserID))

This is a very common beginner mistake. 这是一个非常常见的初学者错误。 The second argument is supposed to be a tuple, list or other similar thing. 第二个参数应该是元组,列表或其他类似的东西。 In this case, you're passing it a string, and each character is treated as an individual value that should be bound. 在这种情况下,您将为它传递一个字符串,并且每个字符都被视为应该绑定的单个值。

You want: 你要:

c.execute("SELECT * FROM users WHERE UserID = ?", (UserID,))

Note the trailing comma to make the argument a one-element tuple. 请注意在末尾加逗号,以使参数成为一个元素的元组。

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

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