Python SQLAlchemy不返回结果中的列名

时间:2019-08-20 19:27:18

标签: python sqlalchemy

非常基本的表,基本的查询。

我的表有以下5列:

project_id, name, job, status, state

我希望查询与特定project_id相关的所有名称。

我收到一个元组作为结果集,其中只有字段值,而没有字段名。

RESULT: ('5', 'bob', 'worker', 'union', '123-456-7890', 'CA')

我将如何修改此查询以在输出中接收字段名称(即列标题)?

DESIRED: {project_id: '5', name:'bob', job:'worker', status:'union', state:'CA'}

代码:

from sqlalchemy import create_engine

def my_engine(db):
    USERNAME = 'admin'
    PASSWORD = 'password'
    HOST = 'localhost'
    DB_PORT = 1234
    DATABASE = str(db)
    return create_engine('mysql+pymysql://{0}:{1}@{2}:{3}/{4}'
                         .format(USERNAME, PASSWORD, HOST, DB_PORT, DATABASE), pool_pre_ping=True)

def query_mysql(self, table_name, col_title, srx_val):
    myconn = my_engine('dbname')
    return_list = myconn.execute("SELECT * FROM `{0}` WHERE `{1}` = '{2}'"
                                .format(table_name, col_title, srx_val)).fetchall()
    return return_list

outdata = self.query_mysql('users', 'project_id', self.PROJ_NUM)

#returns: ('5', 'bob', 'worker', 'union', '123-456-7890', 'CA')

1 个答案:

答案 0 :(得分:-1)

Lucas Lima提供了解决方案here请支持他的答案,而不是这个。

您将按以下方式修改代码:

def query_mysql(self, table_name, col_title, srx_val):
    myconn = my_engine('dbname')
    resproxy = myconn.execute("SELECT * FROM `{0}` WHERE `{1}` = '{2}'"
                                .format(table_name, col_title, srx_val)).fetchall()
    results = []
    if len(data)==0: return results

    for row_number, row in enumerate(resproxy):
        results.append({})
        for column_number, value in enumerate(row):
            results[row_number][row.keys()[column_number]] = value

    return results