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

时间:2018-05-28 10:47:12

标签: python database oracle cx-oracle

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

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

1 个答案:

答案 0 :(得分:0)

您可以单独准备列列表和数据列表,并根据这两个不同的列表构建字典,如下所示:

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