2

I have the below code , and i want to return of my fetch_data_from_db as a dictionary, Currently it is returning a tuple. please let me know what code should be added to the existing to get the same ?

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 Answer 1

1

You can simply prepare the column list and data list separately and build the dictionary based on those two different lists as follows:

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 
Sign up to request clarification or add additional context in comments.

Comments

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.