python pymysql.cursors如何从mysql存储过程中获取INPUT返回结果

Posted

技术标签:

【中文标题】python pymysql.cursors如何从mysql存储过程中获取INPUT返回结果【英文标题】:How python pymysql.cursors get INOUT return result from mysql stored procedure 【发布时间】:2017-02-27 23:37:43 【问题描述】:

我有 mysql 进程:

CREATE DEFINER=`user`@`localhost` PROCEDURE `mysproc`(INOUT  par_a INT(10), IN  par_b VARCHAR(255) , IN  par_c VARCHAR(255), IN  par_etc VARCHAR(255))
    BEGIN
        // bla... insert query here
        SET par_a = LAST_INSERT_ID();
    END$$
DELIMITER ;

测试该 sp,如果我运行:

SET @par_a = -1;
SET @par_b = 'one';
SET @par_c = 'two';
SET @par_etc = 'three';

CALL mysproc(@par_a, @par_b, @par_c, @par_etc);
SELECT @par_a;
COMMIT;

它返回@par_a 我想要的 - 所以我假设我的数据库很好......

那么……

我的python如下:

import pymysql.cursors

def someFunction(self, args):
        # generate Query
        query = "SET @par_a = %s; \
            CALL mysproc(@par_a, %s, %s, %s); \
            SELECT @par_a \
            commit;"

        try:
            with self.connection.cursor() as cursor:
                cursor.execute(query,(str(par_a), str(par_b), str(par_c), str(par_etc)))
                self.connection.commit()
                result = cursor.fetchone()
                print(result) # <-- it print me 'none' how do i get my @par_a result from mysproc above?
                return result
        except:
            raise
        finally:
            self.DestroyConnection()

结果:执行的存储过程,我可以看到记录。

问题:但我无法从上面的 mysproc 中的 python 代码中得到我的@par_a 结果?

如果我改变:

# generate Query
query = "SET @par_a = '" + str(-1) + "'; \
    CALL mysproc(@par_a, %s, %s, %s); \
    SELECT @par_a \
    commit;"

# generate Query
query = "SELECT 'test' \
    commit;"

cursor.execute(query)

奇怪的是,它给了我正确的结果('test',)

【问题讨论】:

您使用cursor.fetchall()cursor.fetchone()。您应该花一点时间阅读这里的文档:pymysql.readthedocs.io/en/latest 谢谢,@Nicarus,我是否需要在 python 的查询变量中进行“选择”才能获得 par_a 结果?或者 fetchone() 会足够聪明来获得我的 par_a 结果?到目前为止我试过了,python print me 'none' T_T 您需要让查询返回您想要的值。编写查询后,您可以使用 fetch 函数在 Python 中返回该结果。 @Nicarus,不工作,我已更新我的问题并更改为您的示例文档,但结果一直向我发送“无” 为什么您在上面的查询与下面的查询不同??? 【参考方案1】:

我使用了这个类,我得到了回应。

import pymysql.cursors

class connMySql:
        def __init__(self, User, Pass, DB, Host='localhost', connShowErr=False, connAutoClose=True):
                self.ShowErr = connShowErr
                self.AutoClose = connAutoClose
                self.DBName = DB
                try:
                        self.connection = pymysql.connect(host=Host,
                             user=User,
                             password=Pass,
                             db=DB, #charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)
                except ValueError as ValErr:
                        if self.ShowErr == True: print(ValErr)
                        return False

        def Fetch(self, Query):
                try:
                        with self.connection.cursor() as cursor:
                                # Read a single record
                                cursor.execute(Query)
                                result = cursor.fetchall()
                        return result
                except ValueError as ValErr:
                        if self.ShowErr == True: print(ValErr)
                        return False
                finally:
                        if self.AutoClose == True: self.connection.close()

        def Insert(self, Query):
                try:
                        with self.connection.cursor() as cursor:
                                # Create a new record
                                cursor.execute(Query)
                        # connection is not autocommit by default. So you must commit to save
                        # your changes.
                        self.connection.commit()
                except ValueError as ValErr:
                        if self.ShowErr == True: print(ValErr)
                        return False
                finally:
                        if self.AutoClose == True: self.connection.close()

        def ProcedureExist(self, ProcedureName):
                try:
                        result = self.Fetch("SELECT * FROM mysql.proc WHERE db = \"" + str(self.DBName) + "\";")
                        Result = []
                        for item in result:
                                Result.append(item['name'])
                        if ProcedureName in Result:
                                return True
                        else:
                                return False
                except ValueError as ValErr:
                        if self.ShowErr == True: print(ValErr)
                        return False

        def CallProcedure(ProcedureName, Arguments=""):
                try:
            # Set arguments as a string value
                        result = self.Fetch('CALL ' + ProcedureName + '(' + Arguments + ')')
                except ValueError as ValErr:
                        if self.ShowErr == True: print(ValErr)
                        return False
                finally:
                        if self.AutoClose == True: self.connection.close()

        def CloseConnection(self):
                try:
                        self.connection.close()
                        return True
                except ValueError as ValErr:
                        if self.ShowErr == True: print(ValErr)
                        return False

def main():
    objMysqlConn = connMySql('user', '1234', 'myDB', connShowErr=True, connAutoClose=False)
    ProcedureName= "mysproc"
    if objMysqlConn.ProcedureExist(ProcedureName):
            result = objMysqlConn.Fetch('CALL ' + ProcedureName + '()')
            if result != False:
                    result = result[0]
                    print(result)
    else:
            print("The procecure does not exist!")

if __name__ == '__main__':
    main()

【讨论】:

以上是关于python pymysql.cursors如何从mysql存储过程中获取INPUT返回结果的主要内容,如果未能解决你的问题,请参考以下文章

(接口自动化)Python3操作MySQL数据库

Mysql在python中的使用:pymysql

python连接数据库

pymysql操作数据库

mysql python pymysql模块 增删改查 查询 字典游标显示

PyMySQL 返回旧/快照值/不重新运行查询?