pythonsqlite

Why does my query not return any rows when my table is not empty?


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?


Solution

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

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