Kiran Gangadharan

Fetching data with a raw SQL query in SQLAlchemy

The following is a sane way of fetching data using a raw SQL query in SQLAlchemy:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16

query = 'select * from books where author=:author'

from sqlalchemy import text
result = yoursession.execute(text(query), {'author': 'Neil Degrasse Tyson'})

from collections import namedtuple
Book = namedtuple('Book', result.keys())

# Create a namedtuple for each row
books = [Record(*r) for r in res.fetchall()]

# Using namedtuple allows you to access attributes using the
# dot operator instead of relying on indexes
for book in books:
    print(book.name, book.author)