我如何从数据库获得数据与列.名(键)?



我使用SQLAlchemy从数据库中提取数据。更具体地说,我使用db。选择方法。因此,我设法仅从列中提取值或仅提取列的名称,但我需要以NAME: VALUE格式提取。帮助如何做到这一点?

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()

对于SQLAlchemy 1.4+,我们可以使用.mappings()以类似字典的格式返回结果:

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'}]

如文档所述,ResultProxy.fetchall()返回RowProxy对象的列表。它们的行为类似于命名元组,但也可以像字典一样使用:

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

更多信息请参见https://docs.sqlalchemy.org/en/13/core/tutorial.html#coretutorial-selecting