Select from SB

Function to select data from a SQLite database and return it as a list of tuples:

import sqlite3

def select_domain_records():
    with sqlite3.connect(DB_BTOB) as conn:
        cur = conn.cursor()
        cur.execute(f"""
            SELECT domain, first, last
            FROM people 
            WHERE domain IS NOT NULL
            AND first IS NOT NULL
            AND last IS NOT NULL
        """)
        rows = cur.fetchall()
    return rows

domains = select_domain_records()

for x in domains:
    print(x[0], x[1], x[2]) # less explicit than dictionary or class records, but shorter function

Function to select data from a SQLite database and return it as a list of objects with attributes from the columns:

import sqlite3

def select_domain_records():
    with sqlite3.connect(DB_BTOB) as conn:
        cur = conn.cursor()
        cur.execute("""
            SELECT email, first, last 
            FROM people 
            WHERE email IS NOT NULL
            AND first IS NOT NULL
            AND last IS NOT NULL
        """)
        rows = cur.fetchall()
        column_names = [description[0] for description in cur.description]

        # Dynamically create a class with the column names as attributes
        RecordClass = type('RecordClass', (object,), {})

        records = []
        for row in rows:
            record = RecordClass()
            for col_name, value in zip(column_names, row):
                setattr(record, col_name, value)
            records.append(record)

    return records

domains = select_domain_records()

for x in domains:   
    print(x.email, x.first, x.last) # more explicit to call & quicker to write than dictionary records but longer function

links

social