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 @ 2020-10-22 10:19  守望人间  阅读(679)  评论(0)    收藏  举报