我有一个存储过程,其中包含多个简化的语句,如下所示
create temp table...;
update temp table...;
....
select * from temp table; #last statement
我有下面的Python代码来从SP获取返回结果。我需要列名,以便将结果转换为 JSON 格式。但是,cursor.description 没有返回我所期望的任何内容。请指教!! Mysql5.7、Oracle 的 mysql-python-connector 2.x、python 3.5
cursor.callproc(proc, args)
columns = cursor.description
print(columns) #returns [('@_sp_get_toc_arg1', 8, None, None, None, None, 1, 128)]
for result in cursor.stored_results():
return result.fetchall()
cursor.stored_results()
返回的迭代器产生游标,您需要检查这些游标的描述以获取列名称,而不是初始游标的描述:
for result in cursor.stored_results():
print(result.description)
return result.fetchall()
需要 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, ...}, ...]
,因此可以进行迭代:
for result in results:
print(result)
如果类似字典的光标不适合您的需要,您可以这样做:
for column_id in cursor.stored_results():
columns = [column[0] for column in column_id.description]
print(columns)