You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中将cx_Oracle.Cursor转换为列表或字典?

如何将cx_Oracle.Cursor转换为列表或字典?

嘿,我来帮你搞定这个问题!你拿到的cx_Oracle.Cursor本质是个可迭代对象,每次迭代会返回一行数据的元组,我们可以轻松把它转成列表或字典结构,下面给你两种实用方案:

一、转成元组组成的列表

这是最直接的方式,用list()就能把Cursor对象转换成由元组组成的列表,每个元组对应一行数据:

import cx_Oracle
conn_str = u'user/pass@IP1:1521/STAT4P'
conn = cx_Oracle.connect(conn_str)
c = conn.cursor()
sql='''select ne,sdate,slot_no,subrack_no,ID_73393960 as HIII,ID_73410486 from Huawei_wcdma.UDSP60 where ne=:name'''

# 执行SQL并传入参数
c.execute(sql, {'name': '你的目标NE名称'})

# 直接转换为列表
result_list = list(c)

# 提取你需要的两列数据(对应SQL里的第5、第6列,索引从0开始)
hiii_data = [row[4] for row in result_list]
target_id_data = [row[5] for row in result_list]

# 用完记得关闭连接
conn.close()

二、转成字典组成的列表

如果想要更直观的键值对结构(用列名作为字典的键),可以借助Cursor的description属性获取列名,再把每行数据和列名一一对应生成字典:

import cx_Oracle
conn_str = u'user/pass@IP1:1521/STAT4P'
conn = cx_Oracle.connect(conn_str)
c = conn.cursor()
sql='''select ne,sdate,slot_no,subrack_no,ID_73393960 as HIII,ID_73410486 from Huawei_wcdma.UDSP60 where ne=:name'''

c.execute(sql, {'name': '你的目标NE名称'})

# 获取所有列的名称
column_names = [col[0] for col in c.description]

# 生成由字典组成的列表
result_dict_list = [dict(zip(column_names, row)) for row in c.fetchall()]

# 提取数据时直接用列名,更清晰
hiii_data = [item['HIII'] for item in result_dict_list]
target_id_data = [item['ID_73410486'] for item in result_dict_list]

conn.close()

小提醒

如果查询结果的数据量特别大,用fetchall()一次性加载所有数据可能会占用过多内存。这时候可以迭代Cursor对象逐行处理,避免内存过载:

c.execute(sql, {'name': '你的目标NE名称'})
column_names = [col[0] for col in c.description]

result_dict_list = []
for row in c:
    row_dict = dict(zip(column_names, row))
    result_dict_list.append(row_dict)
    # 也可以在这里直接处理单条数据,比如实时添加到绘图数据集里

处理完之后,你就能得到适合绘图的纯列表数据,直接传入matplotlib这类绘图库就可以生成图表啦~

内容的提问来源于stack exchange,提问作者Sadegh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:16:28