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

我有以下代码:


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

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


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


呼唤远方
浏览 288回答 2
2回答

RISEBY

之前创建一个变量。将结果分配给您的变量。关闭连接。返回变量。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python