从 python 调用存储过程时获取列名和数据
Getting Column name along with data when calling stored procedure from python
我正在使用 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"
}
您可以从 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
语句有效。
试试这个 - conn.cursor(as_dict=True)
我正在使用 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"
}
您可以从 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
语句有效。
试试这个 - conn.cursor(as_dict=True)