小编典典

cx_Oracle:如何将每一行作为字典接收?

sql

默认情况下,cx_Oracle将每行作为一个元组返回。

>>> import cx_Oracle
>>> conn=cx_Oracle.connect('scott/tiger')
>>> curs=conn.cursor()
>>> curs.execute("select * from foo");
>>> curs.fetchone()
(33, 'blue')

如何将每一行作为字典返回?


阅读 275

收藏
2021-03-17

共1个答案

小编典典

您可以覆盖游标的rowfactory方法。每次执行查询时,都需要执行此操作。

这是标准查询(元组)的结果。

curs.execute('select * from foo')
curs.fetchone()
    (33, 'blue')

返回一个命名的元组:

def makeNamedTupleFactory(cursor):
    columnNames = [d[0].lower() for d in cursor.description]
    import collections
    Row = collections.namedtuple('Row', columnNames)
    return Row

curs.rowfactory = makeNamedTupleFactory(curs)
curs.fetchone()
    Row(x=33, y='blue')

返回字典:

def makeDictFactory(cursor):
    columnNames = [d[0] for d in cursor.description]
    def createRow(*args):
        return dict(zip(columnNames, args))
    return createRow

curs.rowfactory = makeDictFactory(curs)
curs.fetchone()
    {'Y': 'brown', 'X': 1}

感谢Amaury Forgeot d’Arc:http//sourceforge.net/p/cx-
oracle/mailman/message/27145597

2021-03-17