Reputation: 15002
I am using this sample sqlite database and my code is
import sqlite3
conn = sqlite3.connect('chinook.db')
conn.execute("SELECT * FROM tracks")
rows = conn.cursor().fetchall()
It should have worked, but rows
is empty?
What am I doing wrong here?
Upvotes: 17
Views: 21259
Reputation: 12241
The Connection.execute
shortcut returns a cursor
instance, which you need to use with fetchall
. In your code, you're creating a new, independent cursor.
Thus:
import sqlite3
conn = sqlite3.connect('chinook.db')
cursor = conn.execute("SELECT * FROM tracks")
rows = cursor.fetchall()
or even shorter (not recommended, but for those who like obscured one-liners):
rows = sqlite3.connect('chinook.db').execute("SELECT * FROM tracks").fetchall()
Or don't use Connection.execute
shortcut, to avoid confusion:
import sqlite3
conn = sqlite3.connect('chinook.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM tracks")
rows = cursor.fetchall()
Upvotes: 17