如何关闭与 MySQL 库中返回值的连接?

How to close connection with returned value in PyMySQL lib?

我有以下代码:

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

我想将 print(result) 更改为 return 这样我就可以:

value = mysql.get_max_report_date()

但是,如果我将 print(result) 更改为 return result,则不会执行 finally 块。

有没有更好的方法来管理连接和处理错误,同时能够 return 来自查询的值?

之前创建一个变量。将结果分配给您的变量。关闭连接。 Return 变量。

你对 finally 的行为有误。执行 finally 块,即使您有 return 语句。

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

打印"I was executed"

https://ideone.com/KhvVKy