Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

How python pymysql.cursors get INOUT return result from mysql stored procedure

I have mysql proc:

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 ;

to test that sp, if i run:

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;

it return @par_a as what i want - so i assume my db is fine...

then...

i have pyhton as follow:

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()

result: the stored proc executed, as i can see record in.

problem: but i cant get my @par_a result in my python code from mysproc above?

and, if i change:

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

to

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

and

cursor.execute(query)

strangely, it give me the correct result ('test',)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I used this class and I got response.

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...