MySQLdb存储过程输出参数不工作

9 投票
2 回答
9382 浏览
提问于 2025-04-18 09:16

我在谷歌云 SQL 上有一个数据库,还有一个用 Python 写的脚本来查询这个数据库。

我想调用一个存储过程,这个过程有一个输出参数。虽然存储过程调用成功了,但输出参数的值似乎没有返回到我的 Python 代码中。

比如,下面这个例子是从这里拿来的:

这是一个乘法存储过程的定义:

CREATE PROCEDURE multiply(IN pFac1 INT, IN pFac2 INT, OUT pProd INT)
BEGIN
  SET pProd := pFac1 * pFac2;
END

如果我在命令行中这样调用存储过程:

CALL multiply(5, 5, @Result)
SELECT @Result

我能正确得到结果:

+---------+
| @Result |
+---------+
|      25 |
+---------+

但是如果我用 Python 代码,使用 MySQLdb 包这样调用:

args = (5, 5, 0) # 0 is to hold value of the OUT parameter pProd
result = cursor.callproc('multiply', args)
print result

那么我在结果元组中就得不到输出参数:

(5, 5, 0)

那么,我到底哪里做错了呢?

更新:
我刚发现 callproc 代码中有这个警告:

    Compatibility warning: PEP-249 specifies that any modified
    parameters must be returned. This is currently impossible
    as they are only available by storing them in a server
    variable and then retrieved by a query. Since stored
    procedures return zero or more result sets, there is no
    reliable way to get at OUT or INOUT parameters via callproc.
    The server variables are named @_procname_n, where procname
    is the parameter above and n is the position of the parameter
    (from zero). Once all result sets generated by the procedure
    have been fetched, you can issue a SELECT @_procname_0, ...
    query using .execute() to get any OUT or INOUT values.

而且要注意,callproc 函数只是返回相同的输入参数元组。所以总的来说,这是不可能的。看来得重新考虑一下了……

2 个回答

2

看看这个,记得先设置好数据库连接,只需要初始化MYSQL数据库,然后试试下面的内容:

为了让你了解我们在讨论什么,这里是数据库表的定义:

CREATE TABLE table_tmp
(
    data1 INT(11),
    data2 VARCHAR(10),
    data3 TINYINT(1)  -- This will be the output value
);

这是数据库过程的定义:

DROP PROCEDURE IF EXISTS sp_test_tmp;
CREATE DEFINER=`<user_in_the_db>`@`%` PROCEDURE `sp_test_tmp`(

      IN in_data1   INT
    , IN in_data2   VARCHAR(10)
    , IN in_data3   BOOL
    , OUT result    BOOL
)
BEGIN
    INSERT INTO table_tmp
    (
         data1
        ,data2
        ,data3
    )
    VALUES 
    (
        in_data1
        ,in_data2
        ,in_data3
    );
  SET result = FALSE;  -- Setting the output to our desired value
  COMMIT;  -- This will help to update the changes in the database, with variable
           -- the row never will get updated (the select/get a little 
           -- complex less)
END;

Python代码:我在考虑用一组参数来写一个通用的函数;)

TRUE = 1   -- My own definition, for make compatible Mysql and Python Boolean data representation
FALSE = 0

def execute_procedure(pname='sp_test_tmp',pargs=(1,'co@t.com',TRUE,FALSE)):
    try:
        cursor = mysql.connect().cursor()
        status = cursor.callproc(pname, pargs)
        cursor.execute('SELECT @_sp_test_tmp_3') # This is the magic
        result = cursor.fetchone()               # Get the Values from server

        if result[0] == TRUE:
           print ("The result is TRUE")
           resp = True
        elif result[0] == FALSE:
           resp = False
           print("The result is FALSE")
       else:
          resp = False
          print("This is crazy!!!")

       return str(resp)
       except Exception as inst:
         exception = type(inst)
         print(exception)
         return "DON'T"
       finally:
         cursor.close()
13

你只需要再加一个 SELECT 就可以获取输出的值了:

>>> curs.callproc('multiply', (5, 5, 0))
(5, 5, 0)
>>> curs.execute('SELECT @_multiply_0, @_multiply_1, @_multiply_2')
1L
>>> curs.fetchall()
((5L, 5L, 25L),)

撰写回答