如何在PyMySQL lib中使用返回值关闭连接?

时间:2018-11-11 10:04:11

标签: python 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()

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

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

2 个答案:

答案 0 :(得分:0)

之前创建一个变量。将结果分配给变量。关闭连接。返回变量。

答案 1 :(得分:0)

您误会了finally的行为。即使您有return语句,也会执行finally块。

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

打印“我已被处决”

https://ideone.com/KhvVKy