Nuh Yamin
Nuh Yamin

Reputation: 353

How to print output from SQLite 3 in Python

Here is my code:

conn = sqlite3.connect('myfile.db')
print(conn.execute("PRAGMA table_info(mytable);"))

When I ran that, I got this output:

sqlite3.Cursor object at 0x02889FAO

How can I print the actual SQLite 3 output of that?

Upvotes: 5

Views: 11784

Answers (2)

Evgeny A. Mamonov
Evgeny A. Mamonov

Reputation: 1886

You should to fetch results. Here is a working example:

import sqlite3

conn = sqlite3.connect('myfile.db')
cursor = conn.execute("PRAGMA table_info(mytable);")
results = cursor.fetchall()
print(results)

Or with pretty print:

import sqlite3
from pprint import pprint

conn = sqlite3.connect('myfile.db')
cursor = conn.execute("PRAGMA table_info(mytable);")
results = cursor.fetchall()
pprint(results)

Upvotes: 5

Yaroslav Mudryy
Yaroslav Mudryy

Reputation: 11

If you prefer accessing data by column names instead of by index, the provided solution will not be suitable. When fetching the output, SQLite typically returns an sqlite3.Row object rather than a list. To easily view and print this output, you'd want to convert the result to a dictionary.

Here's how you can do it:

import sqlite3 as sl

con = sl.connect('db.sqlite')
con.row_factory = sl.Row
rows = con.execute('SELECT * FROM table').fetchall()

for row in rows:
     print(dict(row))
     print(row['column_name'])

Upvotes: 1

Related Questions