• 上下文管理器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()

  • 相关阅读:
    JSON序列化选项
    JOSN的stringify()和parse()方法
    html5增强元素--续
    html5页面增强元素
    js继承模式
    js常用设计模式
    js跨浏览器事件处理
    前端兴趣浓厚,后端提不起来兴趣
    padding的讲究
    margin的讲究
  • 原文地址:https://www.cnblogs.com/like1824/p/15920899.html
Copyright © 2020-2023  润新知