18

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?

4
  • 2
    You never .execute() the cursor. Commented Oct 15, 2018 at 11:10
  • 1
    @Corion: conn.execute() is a shortcut. It does, however, return the cursor, which is where the problem is. Commented Oct 15, 2018 at 11:13
  • what is the right way to execute cursor(). is it conn.cursor().fetchall(); conn.execute() Commented Oct 15, 2018 at 11:14
  • @Eka: it's all in the documentation. Commented Oct 15, 2018 at 11:17

1 Answer 1

18

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

1 Comment

It's true that the OP was using Python 2, but your code would work perfectly in both versions with the parenthesis added. This is currently one of the top results on Google for using SQLite with Python, so most people seeing your answer are using Python 3. Since OP has probably long since moved on, would you please reconsider making the answer apply to both versions?

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.