Skip to content

Instantly share code, notes, and snippets.

@evjeny
Created May 21, 2023 10:52
Show Gist options
  • Save evjeny/e52021287a4e55187138cea0c344fd51 to your computer and use it in GitHub Desktop.
Save evjeny/e52021287a4e55187138cea0c344fd51 to your computer and use it in GitHub Desktop.
Print prettified tables with SQLite and SQLAlchemy
import sqlite3
import sqlalchemy
def print_formatted_table(table: list[list]):
column_lengths = [
max(len(table[i][column_num]) for i in range(len(table)))
for column_num in range(len(table[0]))
]
for row in table:
print("|", end=" ")
for item, column_length in zip(row, column_lengths):
print(item.rjust(column_length), "|", end=" ")
print()
def print_sqlite_cursor_as_table(title: str, cursor: sqlite3.Cursor):
headers = [d[0] for d in cursor.description]
table: list[list[str]] = [headers]
for row in cursor.fetchall():
table.append(list(map(str, row)))
print(title)
print_formatted_table(table)
print()
def print_sqlalchemy_cursor_as_table(
connection: sqlalchemy.Connection,
title: str,
statement: sqlalchemy.Select,
):
cursor = connection.execute(statement)
headers = list(cursor.keys())
table: list[list[str]] = [headers]
for row in cursor.fetchall():
table.append(list(map(str, row)))
print(title)
print_formatted_table(table)
print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment