gpt4 book ai didi

python-3.x - 从 SQLAlchemy 结果返回字段名称和值

转载 作者:行者123 更新时间:2023-12-01 03:04:14 28 4
gpt4 key购买 nike

如何使用 sqlalchemy 获取表列名称和值?

使用我所拥有的,我能够检索:

(2, 'blue', 'square')

但我想得到的是:

{'id': 2, 'color': 'blue', 'type': 'square'}

贝娄,我看完后写的this documentation for version 0.9 :

ConnectionManager.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sqlalchemy
from sqlalchemy import Table, MetaData
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base


location = 'localhost'
engine_str = 'mysql+mysqlconnector://xx:xx@{}/xx'.format(location)
engine = sqlalchemy.create_engine(engine_str, echo=False)
session = sessionmaker(bind=engine)
connection = engine.connect()
session = session(bind=connection)
metadata = MetaData()
Base = declarative_base()

class SelectType(object):
"""
Server's details on database
"""
def go(self, s, cc, pp):
__table__ = Table('servers', metadata, autoload=True, autoload_with=engine)
result = s.query(__table__).filter_by(color=cc).filter_by(type=pp).all()
return result

def select_type(e, p):
"""
return SelectType result
"""
try:
return SelectType().go(session, e, p)
except:
raise
finally:
session.close()

主文件.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from resources import connection_manager

if __name__ == "__main__":
try:
for i in connection_manager.select_type('blue', 'square'):
print(i)

重要的是要注意我正在使用自动加载

最佳答案

使用Query.column_descriptions给你:

class SelectType(object):
def go(self, s, cc, pp):
__table__ = Table('servers', metadata, autoload=True, autoload_with=engine)
result = s.query(__table__).filter_by(color=environment).filter_by(type=pp)
column_names = [c["name"] for c in result.column_descriptions]
return [dict(zip(column_names, row)) for row in result.all()]

关于python-3.x - 从 SQLAlchemy 结果返回字段名称和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22277548/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com