Forum Stats

  • 3,767,817 Users
  • 2,252,720 Discussions
  • 7,874,336 Comments

Discussions

cx_Oracle cursor - return named tuple

jstem1177
jstem1177 Member Posts: 371
edited Jan 21, 2014 12:47PM in Python

Hello All,

I'm having trouble figuring a way to convert the row returned from a basic execute statement into a named tuple/Dictionary.

The idea, is to be able to access each field via row['column_name']. I'm currently looking at creating a factory, but still a complete noob to python and cx_Oracle.

cur.execute(""SELECT * FROM V$INSTANCE""")
#print 'Query Executed..'
row = cur.fetchone()
#print 'Cursor Loaded.'
#print result[0], result[1]
list = {}
list['host_name'] = row['host_name']
print row['host_name']

Thanks in advance for your assistance.

Jan S.

Best Answer

  • jstem1177
    jstem1177 Member Posts: 371
    Accepted Answer

    Hello All,

    Managed through some weird keyword search to find a nice little article. here is the solution.

    cur = oracle.cursor()
    cur.execute("""SELECT * FROM V$DATABASE""")
    data = rows_to_dict_list(cur)
    for row in data:
    print row['PROTECTION_LEVEL']
    
    
    def rows_to_dict_list(cursor):
    columns = [i[0] for i in cursor.description]
    return [dict(zip(columns, row)) for row in cursor]
    

    Thanks

    Jan S.

    ps - I hate these new editors, Python requires indentations, but that does not mean I want to create and html table from it.

Answers

  • jstem1177
    jstem1177 Member Posts: 371
    Accepted Answer

    Hello All,

    Managed through some weird keyword search to find a nice little article. here is the solution.

    cur = oracle.cursor()
    cur.execute("""SELECT * FROM V$DATABASE""")
    data = rows_to_dict_list(cur)
    for row in data:
    print row['PROTECTION_LEVEL']
    
    
    def rows_to_dict_list(cursor):
    columns = [i[0] for i in cursor.description]
    return [dict(zip(columns, row)) for row in cursor]
    

    Thanks

    Jan S.

    ps - I hate these new editors, Python requires indentations, but that does not mean I want to create and html table from it.

This discussion has been closed.