Making Raw SQL Easier to Read with Row Factory
python sqlite postgreOne thing that annoy me when using raw query in Python is how the returned value is not “easy to remember”. Look at this query:
import sqlite3
con = sqlite3.connect("library.sqlite3")
query = "SELECT id, isbn, title FROM books"
con = con.execute(query)
rows = con.fetchall()
To print the returned value I must remember the index of each field:
for r in rows:
print(f"{r[0]} - {r[1]} - {r[2]}")
# index 0 = id
# index 1 = isbn
# index 2 = title
1 - 1234567890 - Book 1 by Author 1
2 - 2345678901 - Book 1 by Author 1
3 - 3456789012 - Book 1 by Author 1
4 - 4567890123 - Book 1 by Author 2
5 - 5678901234 - Book 1 by Author 2
And if you think it’s only coming from sqlite, you’re wrong. I tried PostgreSQL with psycopg and it has same behavior:
Read more...