3

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); """)
4
  • 3
    Isn't all that stuff supposed to be done inside the with-block? Commented Jun 8, 2021 at 14:43
  • Yes, and also, you aren't actually calling .commit Commented Jun 8, 2021 at 14:44
  • The problem here is the cursor exists between the with indentation. You could push everything inside the with block, or maintain an initial connection and finally close with .close() function. Commented Jun 8, 2021 at 14:46
  • Thank you so much! I didn't know that they need to be indented, can you please just explain why they need to be indented? Commented Jun 8, 2021 at 16:37

1 Answer 1

3

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()
Sign up to request clarification or add additional context in comments.

1 Comment

i think you may remove cursor.close() from your code because with... - its context manager

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.