Using records to query database

records is one of the Kenneth Reitz "for Humans" series.
we can use it to query all kinds of db.

import records
db = records.Database('postgres://...')  # connect to db
rows = db.query('select * from active_users')  # exec SQL
for r in rows:
    print(r.name, r.user_email)
print(rows.dataset)
# username|active|name      |user_email       |timezone
# --------|------|----------|-----------------|--------------------------
# model-t |True  |Henry Ford|model-t@gmail.com|2016-02-06 22:28:23.894202
# export to different format
print(rows.export('json'))  # json
print(rows.export('csv'))  # csv
print(rows.export('yaml')) # yaml
rows.export('df')  # pandas df
with open('report.xls', 'wb') as f:
    f.write(rows.export('xls'))  # xls

Leave a Reply

Your email address will not be published. Required fields are marked *