简体   繁体   English

我如何使用 column.names(keys) 从 DB 获取数据?

[英]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.

相关问题 pandas 在我使用时间戳列查询时自动转换时间戳列? 如何获得与 postgres 数据库中相同的数据? - pandas automatically converting timestamp columns when i query using timestamp columns? how can i get the same data as it is in the postgres db? 如何从嵌套字典中获取键? - How can I get the keys from a nested dictionary? 如何从名称列表中获取 0/1 的标签? - How can I get tags of 0/1 from list of names? 如何从sklearn TruncatedSVD对象获取功能名称? - How can I get the feature names from sklearn TruncatedSVD object? 如何从taxid获得分类等级名称? - How can I get taxonomic rank names from taxid? 如何从 keras 模型中获取输出节点名称? - How can I get output node names from a keras model? 如何创建将键名指定为输入变量的字典 - How can I create dictionary specifying keys names as a input variable 如何从第二个来源获取数据以流入适当的列? - How can I get data from a second source to flow into proper columns? 如何在从弹性搜索导出的CVS文件中打印出列名? - How can I print out columns names in my CVS file that is exported from elastic search? 如何从数据库获取电子邮件配置? - How can I get the email configuration from the DB?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM