11

My code to query an sqlite3 database:

import sqlite3 as lite

conn = lite.connect('db/posts.db')
cur = conn.cursor()

def get_posts():
    cur.execute("SELECT * FROM Posts")
    print(cur.fetchall())

get_posts()

I have already created the table Posts. I get no errors, it just prints []. The table isn't empty, I created it in a REPL. Why is this not working?

2 Answers 2

12

Use a context manager, so you don´t have to commit!

def get_posts():
    with conn:
        cur.execute("SELECT * FROM Posts")
        print(cur.fetchall())
Sign up to request clarification or add additional context in comments.

1 Comment

You wouldn't have to commit anyway because the statement being executed does not modify the database
11

Turns out I just forgot to use conn.commit(). Hope this helps someone.

2 Comments

Actually, why would you need to add a commit if the data is not modified? Is that a sqlite thing?
Seems like this question should just have been deleted, since there's nothing wrong with the posted code. The table actually was empty because you had a bug in the code that was supposed to populate it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.