starscape
starscape

Reputation: 2973

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?

Upvotes: 11

Views: 59078

Answers (2)

Martin
Martin

Reputation: 164

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

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

Upvotes: 12

starscape
starscape

Reputation: 2973

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

Upvotes: 11

Related Questions