使用sqlite3和python更新表

时间:2018-03-10 20:41:44

标签: python sqlite

我正在尝试使用sqlite3和python更新名为'stats'的表。该表具有结构[username, correct, total]。这是我正在使用的代码:

        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

但是,表中的值永远不会更新。 new_correct和new_total正确返回。此外,有没有一种方法来更新,而无需先调用以前的值?我只需要将总计增加1并按0或1校正,具体取决于正确的输入是什么?

1 个答案:

答案 0 :(得分:0)

已解决,我不得不将更新命令中的和更改为逗号。现在它写着:

Serializer