如何使用 python、cx_oracle 获取查询的结果集作为字典?

How to fetch result set of a query as dictionary using python, cx_oracle?

我有下面的代码,我想 return 我的 fetch_data_from_db 作为字典,目前它是 returning 一个元组。请让我知道应该将哪些代码添加到现有代码中以获得相同的代码?

import cx_Oracle

class OracleDBConnection(object):

    def connect_oracle_db(self,connectionstring):    
        con=None
        try:
            con = cx_Oracle.connect(connectionstring)
            return con
        except Exception as e:
            print str(e.args)
            print str(e)
            return str(e)
    #print con.version

    def fetch_data_from_db(self,con, query):         
        curs = con.cursor()   
        curs.execute(query)          
        res=curs.fetchall() 
        return res

您可以简单地分别准备列列表和数据列表,然后根据这两个不同的列表构建字典,如下所示:

def fetch_data_from_db(self, con, query):         
    curs = con.cursor()   
    curs.execute(query)  

    # list of table columns
    column_names = list(map(lambda x: x.lower(), [
            d[0] for d in curs.description]))
    # list of data items
    rows = list(curs.fetchall())

    result = [dict(zip(column_names, row)) for row in rows]
    return result