gpt4 book ai didi

python - cx_Oracle : How can I receive each row as a dictionary?

转载 作者:太空狗 更新时间:2023-10-29 20:42:00 30 4
gpt4 key购买 nike

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

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

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

最佳答案

您可以覆盖游标的 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

关于python - cx_Oracle : How can I receive each row as a dictionary?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35045879/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com