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?
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With