从Python调用存储过程时获取列名和数据

问题描述 投票:0回答:3

我正在使用 cx_Oracle 包从 python 调用 PL/SQL 存储过程。 PL/SQL 存储过程返回 SYS_REFCURSOR 作为 OUT 参数。我能够获取 REF_CURSOR 的值,但无法获取列的名称和值。

PFB我的代码

result_set = self.__cursor__.callproc(call_procedure, parameters)    
result_set[index].fetchall()

fetchall() 仅返回数组中的值,如

[
  "John",
  "B",
  "Doe",
  "111223333",
  "Fri, 09 May 1997 00:00:00 GMT",
  "212 Main St, Orlando, FL",
  "M",
  25000,
  "333445555"
]

但我想要这样的东西

{
  "FirstName": "John",
  "MInit": "B",
  "LastName": "Doe",
  "SSN": "111223333",
  "DOE": "Fri, 09 May 1997 00:00:00 GMT",
  "Addr": "212 Main St, Orlando, FL",
  "Sex": "M",
  "Sal": 25000,
  "DNO": "333445555"
}
python cx-oracle
3个回答
9
投票

您可以从

cursor.description
获取所有列名称,并使用
zip()
函数构建字典列表:

# prepare cursor and execute procedure
conn = ...
cursor = conn.cursor()
cursor.callproc(...)

# get only column names from cursor description
column_names_list = [x[0] for x in cursor.description]

# construct a list of dict objects (<one table row>=<one dict>) 
result_dicts = [dict(zip(column_names_list, row)) for row in cursor.fetchall()]

对于

SELECT
陈述也应该有效。


1
投票

试试这个 - conn.cursor(as_dict=True)


0
投票

在调用过程后获取列名称的最简单方法是在存储结果上使用

next
内置函数:

columns = next(cursor.stored_results()).column_names

但我认为当需要 JSON 格式时,最好的方法是使用 类似字典的光标

dict_cursor = connection.cursor(dictionary=True)
dict_cursor.callproc("proc")
results = next(dict_cursor.stored_results()).fetchall()

results 变量是一个列表,其中包含每个检索到的记录的对象,以列名作为键

[{column_name: first_row_value, ...}, {column_name: second_row_value, ...}, ...]

© www.soinside.com 2019 - 2024. All rights reserved.