Search code examples
pythonpymysql

How to close connection with returned value in PyMySQL lib?


I have the following code:

import pymysql.cursors
class MylocalSQL:

    def __init__(self):
        pass

    def get_max_report_date(self):
        connection = pymysql.connect(host=...,
                                     charset='utf8mb4',
                                     cursorclass=pymysql.cursors.DictCursor)
        try:
            with connection.cursor() as cursor:
                # Read a single record
                sql = "SELECT value from tab limit 1 "
                cursor.execute(sql)
                result = cursor.fetchone()
                print(result)
        finally:
            connection.close()


if __name__ == '__main__':
    mysql = MylocalSQL()
    mysql.get_max_report_date()

I want to change the print(result) into return so i can do:

value = mysql.get_max_report_date()

However if I change the print(result) into return result then the finally block won't be executed.

Is there a better way to manage the connection & handling errors while being able to return the value from the query?


Solution

  • You are mistaken about the behavior of finally. The finally block is executed, even if you have the return statement.

    class MylocalSQL:
    
        def __init__(self):
            pass
    
        def get_max_report_date(self):
            try:
                return "some value"
            finally:
                print('i was executed')
    
    
    MylocalSQL().get_max_report_date()
    

    prints "I was executed"

    https://ideone.com/KhvVKy