Pregunta

This is how I process the records from a db in Python

code.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]

Question: Instead of hardcoding as row[0],row[1], Is there a way to get the column names directly ?

¿Fue útil?

Solución

The cursor has a .description attribute; it's a sequence of tuples. Each tuple describes a column in the result and it's first value is the name.

You can use it to construct a dict of each row:

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

The .description attribute is described in more detail in the Python DB API 2.0.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top