0

这就是我在 Python 中处理来自数据库的记录的方式

代码.py

conn = cx_Oracle.connect('pass the connection string')
cursor = conn.cursor()
sql = "select * from emp table"
cursor.execute(sql)
result =cursor.fetchall()

for row in result:
     name = row[0]
     age  = row[1]

问题:有没有办法直接获取列名,而不是硬编码为 row[0],row[1]?

4

1 回答 1

1

cursor一个.description属性;这是一个元组序列。每个元组描述结果中的一列,它的第一个值是名称。

您可以使用它来构造每一行的字典:

for x in result:
    row = { d[0].lower(): col for (d, col) in zip(cursor.description, x) }
    name = row['name']
    age = row['age']

该属性在Python DB API 2.0.description中有更详细的描述。

于 2012-09-27T21:57:16.110 回答