dimanche 16 avril 2017

Querying a SQLAlchemy automap reflected Postgres database

I am in the process of teaching myself SQLAlchemy in Python from a variety of examples on the web and Essential SQLAlchemy (very helpful in clarifying things) I need help in understanding how to access query results with the following functional automapping code.

When attempting to print results from a table I receive the following error, though I can see that the class and table name have been reflected:

NameError: name 'test' is not defined

what would allow printing a single filtered record or all rows and columns, essentially a fetchall(). I did ensure that automapped table has a primary key as required.

Code

from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.automap import automap_base

engine = create_engine('your database URI')
m = MetaData() #defaults to 'public' if schema='public' is left out
b = automap_base(bind=engine, metadata=m) b.prepare(engine, reflect=True)

#working, prints out automapped classes
for mappedclass in b.classes:
    print(mappedclass)

#working, prints out automapped tables
for mdtable in m.tables:
    print(mdtable)

#not working, print resulting columns
    for c in sqlalchemy.ext.automap.history_1m.c:
    print(c)

Traceback

Classes: 
Traceback (most recent call last):

    for c in sqlalchemy.ext.automap.test.c:
<class 'sqlalchemy.ext.automap.test'>
NameError: name 'sqlalchemy' is not defined
<class 'sqlalchemy.ext.automap.test'>

Tables: 

test

Process finished with exit code 1

Thank you for your help.





Aucun commentaire:

Enregistrer un commentaire