默认情况下,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 Forgot d'Arc信贷:
http://sourceforge.net/p/cx-oracle/mailman/message/27145597