What is the purpose of the row_factory method of an sqlite3 Connection object?

Viewed 18594

Somehow the docs didn't make it too clear for me. I'm having trouble understanding the purpose of row_factory method of an sqlite3 Connection object.

Basically, could you explain the following snippet?

def connect_db():
    """Connects to the specific database."""
    rv = sqlite3.connect(app.config['DATABASE'])
    rv.row_factory = sqlite3.Row
    return rv
2 Answers

The line of code assigning sqlite3.Row to the row_factory of connection creates what some people call a 'dictionary cursor', - instead of tuples it starts returning 'dictionary' rows after fetchall or fetchone.

The pretty standard example:

import sqlite3 as sqlite

conn = sqlite.connect('companies_db.sqlite')

with conn:
    conn.row_factory = sqlite.Row
    curs = con.cursor()
    curs.execute("SELECT * FROM companies_table")
    rows = curs.fetchall()
    for row in rows:
        print(f"{row['companyid']}, {row['name']}, {row['address']}.")
Related