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. newname and newgrade are also successfully fetched in this function, just not passed to the database.
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); """)
asked Jun 8, 2021 at 14:42
Qianghao Ken Wu
311 silver badge5 bronze badges
1 Answer 1
You need to indent all your code to be inside the with block, and call the commit() function with parenthesis. Also, you should probably close the cursor once you're done inserting values.
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()
answered Jun 8, 2021 at 14:46
Gavin Wong
1,2701 gold badge9 silver badges17 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Sergey Ilyin
i think you may remove
cursor.close() from your code because with... - its context managerdefault
.commit.close()function.