Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch data from sqlite using python?

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()

for row in rows:
    print row

It should have worked but there is no output? What am I doing wrong here?

like image 941
Eka Avatar asked Oct 15 '18 11:10

Eka


People also ask

How would you retrieve data from SQLite table?

We can retrieve anything from database using an object of the Cursor class. We will call a method of this class called rawQuery and it will return a resultset with the cursor pointing to the table. We can move the cursor forward and retrieve the data. This method return the total number of columns of the table.

Can I use SQLite with Python?

SQLite is a self-contained, file-based SQL database. SQLite comes bundled with Python and can be used in any of your Python applications without having to install any additional software.


1 Answers

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:

from __future__ import print_function
import sqlite3

conn = sqlite3.connect('chinook.db')
cursor = conn.execute("SELECT * FROM tracks")
rows = cursor.fetchall()

for row in rows:
    print(row)

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:

from __future__ import print_function
import sqlite3

conn = sqlite3.connect('chinook.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM tracks")
rows = cursor.fetchall()

for row in rows:
    print(row)
like image 161
9769953 Avatar answered Oct 11 '22 06:10

9769953