Skip to content Skip to sidebar Skip to footer

How Do I Print Tables From An SQLite Databse In Python?

So I have a database of information that I would like to print in a nice table format, held as an SQLite db file. The only print statements I have seen print the information in a

Solution 1:

Adding column names to your rows using row_factory is well documented:

import sqlite3

con = sqlite3.Connection('my.db')
con.row_factory = sqlite3.Row

cur = con.cursor()
cur.execute('SELECT * FROM tbl')

for row in cur.fetchall():
     # can convert to dict if you want:
     print(dict(row))

You could then use str.rjust and related functions to print the table, or use a csv.DictWriter with sys.stdout as the "file":

import csv
import sys

wtr = csv.DictWriter(sys.stdout, fieldnames=[i[0] for i in cur.description])
wtr.writeheader()

for row in cur.fetchall():
    wtr.writerow(dict(row))

Post a Comment for "How Do I Print Tables From An SQLite Databse In Python?"