简体   繁体   English

使用sqlite3和python更新表

[英]Updating table using sqlite3 and python

I am trying to update a table titled 'stats' using sqlite3 and python. 我正在尝试使用sqlite3和python更新名为“ stats”的表。 The table has the structure [username, correct, total] . 该表具有[username, correct, total] This is the code I'm using: 这是我正在使用的代码:

        conn = sqlite3.connect(stats_db)  # connect to that database (will create if it doesn't already exist)
        c = conn.cursor()  # make cursor into database (allows us to execute commands)
        outs = ""

        try:
            c.execute('''CREATE TABLE stats (username text,correct int, total int);''') # run a CREATE TABLE command
            outs = "database constructed"

        except:
            things = c.execute('''SELECT * FROM stats;''').fetchall()
            output_list = []
            for x in things:
                output_list.append(x)
            new_correct = output_list[0][1] + int(correct)
            new_total = output_list[0][2] + 1
            c.execute('''UPDATE stats SET correct = (?) and total = (?) where username = (?);''',(new_correct, new_total, username))

            things = c.execute('''SELECT * FROM stats;''').fetchall() #
            outs = "Things:\n"
            output_list = []
            for x in things:
                output_list.append(x)
            outs += str(output_list)
            conn.commit() # commit commands
            conn.close() # close connection to database
        return outs

However, the values in the table never get updated. 但是,表中的值永远不会更新。 new_correct and new_total are returning correctly. new_correct和new_total正确返回。 Also, is there a way to update without first calling the previous values? 另外,有没有一种方法可以在不先调用先前值的情况下进行更新? I just need to increment total by 1 and correct by either 0 or 1 depending on what the input of correct is? 我只需要将总数加1并根据0或1进行校正,具体取决于正确的输入是什么?

Resolved, I had to change the and in my update command to a comma. 解决后,我必须将update命令中的and更改为逗号。 Now it reads: 现在显示:

c.execute('''UPDATE stats SET correct = ?, total = ? where username = ?;''',(new_correct, new_total, username))

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

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