python sqlalchemy get column names dynamically?

2019-01-26 08:41发布

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from sqlalchemy import create_engine

connection = create_engine('mysql://user:passwd@localhost:3306/db').connect()

result = connection.execute("select * from table")
for v in result:
        print v['id']
        print v['name']
connection.close()

how i can get TABLES COLUMNS NAMES dynamically? in this case id and name

2条回答
神经病院院长
2楼-- · 2019-01-26 09:04

something like this

headers=[ i[0] for i in result.cursor.description ]

same question here return column names from pyodbc execute() statement

查看更多
看我几分像从前
3楼-- · 2019-01-26 09:06

You can either find the columns by calling result.keys() or you can access them through calling v.keys() inside the for loop.

Here's an example using items():

for v in result:
    for column, value in v.items():
        print('{0}: {1}'.format(column, value))
查看更多
登录 后发表回答