上下文管理器--with用法

连接数据库后,需要释放链接,此时想到用上下文管理器来提高效率,具体代码如下:

import pymysql


class Cal:
    def __enter__(self):
        # 连接数据库
        print("连接数据库")
        self.conn = pymysql.connect('127.0.0.1', port=3306, database='aresresource', user='aresresource',
                                    password='aresresource123', charset='utf8')
        self.cursor = self.conn.cursor()
        return self

    def test1(self):
        selectsql = 'select * from tm_ed_time_task;'
        self.cursor.execute(selectsql)
        result = self.cursor.fetchall()
        print(result)

    def __exit__(self, type, value, traceback):
        print("关闭数据库链接")
        self.conn.close()


def test1pro():
    with Cal() as cal:
        cal.test1()


if __name__ == '__main__':
    test1pro()

实现过程遇到的问题:

1.__enter__函数:with 后会将__enter__函数返回给上下文管理器对象

相当于 cal = Cal()

 

posted @ 2022-02-21 22:06  linma  阅读(69)  评论(0)    收藏  举报