mysqlclient执行存储过程获取输出参数

使用mysqlclient执行存储过程时,按正常的方法无法获取输出参数。使用如下方法获取:

复制代码
conn = MySQLdb.connect(**self.settings)
cursor = conn.cursor()
args = ('in', 'in', 'out') # 两个输入参数,一个输出参数
cursor.callproc(procedure_name, args)
print(cursor.fetchall()) # 获取存储过程中的查询结果,当有多个查询结果时使用cursor.nextset()获取
# print(cursor.nextset())
# 查询参数值,格式:@_procedure_name_传入参数时参数的位置
cursor.execute(f"select @_{procedure_name}_0, @_{procedure_name}_1, @_{procedure_name}_2")
print(cursor.fetchall())
cursor.close()
conn.close()
复制代码

参考:

callproc(procname, args)

Calls stored procedure procname with the sequence of arguments in args. Returns the original arguments. Stored procedure support only works with MySQL-5.0 and newer.

Compatibility note: PEP-249 specifies that if there are OUT or INOUT parameters, the modified values are to be returned. This is not consistently possible with MySQL. Stored procedure arguments must be passed as server variables, and can only be returned with a SELECT statement. Since a stored procedure may return zero or more result sets, it is impossible for MySQLdb to determine if there are result sets to fetch before the modified parmeters are accessible.

The parameters are stored in the server as @_*procname*_*n*, where n is the position of the parameter. I.e., if you cursor.callproc(‘foo’, (a, b, c)), the parameters will be accessible by a SELECT statement as @_foo_0, @_foo_1, and @_foo_2.

Compatibility note: It appears that the mere act of executing the CALL statement produces an empty result set, which appears after any result sets which might be generated by the stored procedure. Thus, you will always need to use nextset() to advance result sets.

 

posted @   守望人间  阅读(660)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示