0

I am using SQLAlchemy to pull data from my database. More specifically, I use the db.select method. So I manage to pull out only the values from the columns or only the names of the columns, but I need to pull out in the format NAME: VALUE. Help how to do this?

 connection = engine.connect()
    metadata = db.MetaData()
    report = db.Table('report', metadata, autoload=True, autoload_with=engine)
    query = db.select([report])
    ResultProxy = connection.execute(query)
    ResultSet = ResultProxy.fetchall()
 

2 Answers2

0

As the docs state, ResultProxy.fetchall() returns a list of RowProxy objects. These behave like namedtuples, but can also be used like dictionaries:

>>> ResultSet[0]['column_name']
column_value

For more info, see https://docs.sqlalchemy.org/en/13/core/tutorial.html#coretutorial-selecting

Jesse Bakker
  • 2,403
  • 13
  • 25
0

With SQLAlchemy 1.4+ we can use .mappings() to return results in a dictionary-like format:

import sqlalchemy as sa

# …

t = sa.Table(
    "t",
    sa.MetaData(),
    sa.Column("id", sa.Integer, primary_key=True, autoincrement=False),
    sa.Column("txt", sa.String),
)
t.create(engine)

# insert some sample data
with engine.begin() as conn:
    conn.exec_driver_sql(
        "INSERT INTO t (id, txt) VALUES (1, 'foo'), (2, 'bar')"
    )

# test code
with engine.begin() as conn:
    results = conn.execute(select(t)).mappings().fetchall()
    pprint(results)
    # [{'id': 1, 'txt': 'foo'}, {'id': 2, 'txt': 'bar'}]
Gord Thompson
  • 116,920
  • 32
  • 215
  • 418