简体   繁体   English

如何将值插入到 Python 中的 SQLite3 数据库中?

[英]How to insert value into a SQLite3 database in Python?

I have the following function which inserts two values into my database, however, no matter how many times I try, the data is just not inserted.我有以下 function 将两个值插入我的数据库,但是,无论我尝试多少次,数据都没有插入。 newname and newgrade are also successfully fetched in this function, just not passed to the database. newname 和 newgrade 在这个 function 中也成功获取,只是没有传到数据库中。

def addtolist():
    with sqlite3.connect("TestScore.db") as db:
            cursor = db.cursor()
    newname = sname.get()
    newgrade = sgrade.get()
    cursor.execute("""INSERT INTO Scores(name,score) VALUES (?,?)""", (newname, newgrade))
    db.commit
    sname.delete(0, END)
    sgrade.delete(0, END)
    sname.focus()

And I created the database like following我创建了如下数据库

cursor.execute(""" CREATE TABLE IF NOT EXISTS Scores (id integer PRIMARY KEY, name text, score integer); """)

You need to indent all your code to be inside the with block, and call the commit() function with parenthesis.您需要将所有代码缩进到with块内,并用括号调用commit() function。 Also, you should probably close the cursor once you're done inserting values.此外,您可能应该在完成插入值后关闭 cursor。

Try the code below to see if it works:试试下面的代码,看看它是否有效:

def addtolist():
    with sqlite3.connect("TestScore.db") as db:
            cursor = db.cursor()
        newname = sname.get()
        newgrade = sgrade.get()
        cursor.execute("""INSERT INTO Scores(name,score) VALUES (?,?)""", (newname, newgrade))
        db.commit()
        sname.delete(0, END)
        sgrade.delete(0, END)
        sname.focus()
        cursor.close()

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

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