无法从数据库记录中读取sqlite3 python

问题描述

这是我第一次使用sqlite3,并且正在使用数据库。我正在做一个在线井字游戏,这样我就可以和朋友一起玩。在def dataRead():中,我试图读取用户注册窗口输入的数据,并且试图检查数据是否已经保存在数据库中。如果是,则用户必须输入另一个用户名

    def register():
        ##initialising sqlite
        con = sqlite3.connect("userData.db")
        c = con.cursor()
        def submit():
            #creating tables in the database
            def createTable():
                c.execute("CREATE TABLE IF NOT EXISTS userInfo(username TEXT,password TEXT)")

            def dataRead():
                username = user.get()
                password = pword.get()
                c.execute("SELECT username FROM userInfo")
                data = c.fetchall()
                try:
                    for row in data:
                        if row == username:
                            Label(regWin,text = "Sorry,username already in use...\nTry another one.",fg = "red").pack()
                            print(data)
                        else:
                            dataEntry(username,password)
                except TypeError:
                    dataEntry(username,password)
                    
            def dataEntry(username,password):
                c.execute("INSERT INTO userInfo(username,password) VALUES (?,?)",(username,password))
                con.commit()
                
            createTable()
            dataRead()
        



我尝试使用c.fetchall()来读取usernameuserInfo的记录,以便程序可以检查用户名是否可用,但似乎不起作用(至少对我来说)。

解决方法

fetchall 方法返回一个元组列表,无论是选择一列还是多列。因此,if row == username:处的比较将永远是不正确的。如果要使用元组的第一个元素,则通常使用row[0]

,

返回的记录是元组,因此您需要使用row[0] == username代替:

def dataRead():
    username = user.get()
    password = pword.get()
    
    c.execute("SELECT username FROM userInfo")
    data = c.fetchall()
    found = False
    for row in data:
        if row[0] == username:
            found = True
            Label(regWin,text = "Sorry,username already in use...\nTry another one.",fg = "red").pack()
            print(row)
            break
    if not found:
        dataEntry(username,password)

但是,您不需要从数据库中获取所有记录。您可以使用WHERE子句获取所需的记录:

def dataRead():
    username = user.get()
    password = pword.get()

    c.execute('SELECT username FROM userInfo WHERE username = ?',(username,))
    data = c.fetchone()
    if data:
        Label(regWin,fg = "red").pack()
        print(data)
    else:
        dataEntry(username,password)

另外,最好将username字段设为唯一字段:

def createTable():
    c.execute("CREATE TABLE IF NOT EXISTS userInfo(username TEXT PRIMARY KEY,password TEXT)")

因此表中没有重复的用户名。