Python processing sql records
문제
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 ?
해결책
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.
제휴하지 않습니다 StackOverflow