[英]How i can get data from DB with columns.names(keys)?
I am using SQLAlchemy to pull data from my database.我正在使用 SQLAlchemy 从我的数据库中提取数据。 More specifically, I use the db.select method.
更具体地说,我使用 db.select 方法。 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.
因此,我设法仅从列中提取值或仅提取列名称,但我需要以 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()
As the docs state, ResultProxy.fetchall()
returns a list of RowProxy
objects.正如文档所述,
ResultProxy.fetchall()
返回一个RowProxy
对象列表。 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有关更多信息,请参阅https://docs.sqlalchemy.org/en/13/core/tutorial.html#coretutorial-selecting
With SQLAlchemy 1.4+ we can use .mappings() to return results in a dictionary-like format:使用 SQLAlchemy 1.4+,我们可以使用.mappings()以类似字典的格式返回结果:
t = Table(
"t",
sa.MetaData(),
Column("id", Integer, primary_key=True, autoincrement=False),
Column("txt", 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'}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.