Skip to content

Fetch cursor rows as list of dict #410

@rafaelreuber

Description

@rafaelreuber

Convert a cursor result set into a list of dictionary is a very common pattern, mainly when you are coding APIs that returns data as json. A list of dict is a versatile data structure to deal with other things like csv files or pandas dataframes.

The following implementation show how we can do it using cx_Oracle 7.3

import cx_Oracle

class Connection(cx_Oracle.Connection):

    def __init__(self, *args,  **kwargs):
        return super(Connection, self).__init__(*args, **kwargs)

    def cursor(self):
        return Cursor(self)


class Cursor(cx_Oracle.Cursor):

    def dictfecthall(self):
        columns = [col[0] for col in self.description]
        _data = [
            dict(zip(columns, row)) for row in self.fetchall()]
        return _data


conn = Connection("user", "pwd",  "localhost:1521/ebs", encoding="UTF-8")

with conn.cursor() as cursor:
    cursor.execute("select * from hr.employee")
    data = cursor.dictfecthall()
    return data

I think if cx_Oracle bring this by default, it can be a more powerful and versatile tool.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions