用Rowfactories改变 cx_Oracle 查询返回结果为 字典 形式
原创
©著作权归作者所有:来自51CTO博客作者小龙在山东的原创作品,请联系作者获取转载授权,否则将追究法律责任
cx_Oracle查询结果,默认返回元组数据,如果想返回字典形式数据,最简单的方式是修改Rowfactories方法。
cx_Oracle “rowfactories” are methods called for each row that is
retrieved from the database. The Cursor.rowfactory() method is called
with the tuple that would normally be returned from the database. The
method can convert the tuple to a different value and return it to the
application in place of the tuple.
cursor.execute("select * from locations where location_id = 1000")
columns = [col[0] for col in cursor.description]
cursor.rowfactory = lambda *args: dict(zip(columns, args))
data = cursor.fetchone()
print(data)
参考:https://cx-oracle.readthedocs.io/en/latest/user_guide/sql_execution.html?highlight=dict#fetch-data-types