0

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 ?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

+1. You had two minor typos, but the basic idea is exactly right.
dict= {}.....dict1 = { d[0].lower():col for(d, col) in zip(self.cursor.description, row) }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.