PYODBC调用存储过程仅返回首个查询结果的求助
解决PYODBC调用存储过程仅返回第一个结果集的问题
你的存储过程包含5个独立的SELECT语句,每个语句都会生成一个单独的结果集。PYODBC默认只会读取第一个结果集,要获取所有查询结果,需要手动遍历所有结果集。
修改后的PYODBC执行代码
def user_query(user, conn, output_field): # 移除多余的global声明,避免参数变量冲突 user_results = [] username = user.get() cursor = conn.cursor() get_user_stored_proc = "SET NOCOUNT ON; EXEC [dbo].[getUser] @username = ?" output_field.config(state=NORMAL) output_field.delete('1.0', END) cursor.execute(get_user_stored_proc, username) # 循环遍历所有结果集 while cursor.description: # 获取当前结果集的列名 columns = [column[0] for column in cursor.description] # 读取当前结果集的所有行 for row in cursor: user_results.append(dict(zip(columns, row))) # 切换到下一个结果集 cursor.nextset() print_results(user_results, output_field) # cursor.close() # conn.close()
代码说明
cursor.description:当存在可读取的结果集时,该属性会返回结果集的列信息;当所有结果集都处理完毕后,会返回None,循环终止。cursor.nextset():手动切换到下一个结果集,每次处理完当前结果集的所有行后调用该方法。- 移除了多余的
global user声明:函数参数已经传入user,全局声明会导致变量冲突,属于冗余代码。
内容的提问来源于stack exchange,提问作者Buzzkillionair
相关产品推荐
相关产品推荐

