码迷,mamicode.com
首页 > 其他好文 > 详细

让对象支持with语句

时间:2018-12-09 17:24:44      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:sql数据库   分享   句柄   self   操作   data   exe   commit   技术分享   

技术分享图片
一、with语句的好处
with语句的好处在于,它可以自动帮我们释放上下文,就比如文件句柄的操作,
如果你不使用with语句操作,你要先open一个文件句柄,使用完毕后要close这个文件句柄,
而使用with语句后,退出with代码块的时候就会自动帮你释放掉这个文件句柄。
场景使用:
    网络连接、数据库连接、文件句柄、锁



二、如何让对象支持with语句
方法:
在创建类的时候,在内部实现__enter__方法,with语句一开始就会执行这个方法,
再实现__exit__方法,退出with代码块的时候会自动执行这个方法。

例子:
class A:
    def __enter__(self):
        print(with语句开始)
        return self  # 返回self就是把这个对象赋值给as后面的变量

    def __exit__(self, exc_type, exc_val, exc_tb):
        print(with语句结束)


with A() as f:
    print(IG牛批)
    print(f)
print(IG真的牛批)

结果:
with语句开始
IG牛批
<__main__.A object at 0x0000027B4D1596D8>
with语句结束
IG真的牛批



三、使用with语句优化pymysql的操作
1、使用with语句连接pymysql数据库基本操作
import pymysql

class SQLManager(object):
    # 初始化实例的时候调用connect方法连接数据库
    def __init__(self):
        self.conn = None
        self.cursor = None
        self.connect()
        
    # 连接数据库
    def connect(self):
        self.conn = pymysql.connect(
            host=127.0.0.1,
            port=3306,
            database=mydb,
            user=root,
            password=123abc,
            charset=utf8
        )
        self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)

    # 关闭数据库
    def close(self):
        self.cursor.close()
        self.conn.close()
        
    # 进入with语句自动执行    
    def __enter__(self):
        return self
        
    # 退出with语句自动执行    
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()


2、还可以在上面的基础上实现pymysql的一些操作
class SQLManager(object):

    # 初始化实例方法
    def __init__(self):
        self.conn = None
        self.cursor = None
        self.connect()

    # 连接数据库
    def connect(self):
        self.conn = pymysql.connect(
            host=127.0.0.1,
            port=3306,
            database=mydb,
            user=root,
            password=123abc,
            charset=utf8
        )
        self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)

    # 查询多条数据sql是sql语句,args是sql语句的参数
    def get_list(self, sql, args=None):
        self.cursor.execute(sql, args)
        result = self.cursor.fetchall()
        return result

    # 查询单条数据
    def get_one(self, sql, args=None):
        self.cursor.execute(sql, args)
        result = self.cursor.fetchone()
        return result

    # 执行单条SQL语句
    def moddify(self, sql, args=None):
        self.cursor.execute(sql, args)
        self.conn.commit()

    # 执行多条SQL语句
    def multi_modify(self, sql, args=None):
        self.cursor.executemany(sql, args)
        self.conn.commit()

    # 创建单条记录的语句
    def create(self, sql, args=None):
        self.cursor.execute(sql, args)
        self.conn.commit()
        last_id = self.cursor.lastrowid
        return last_id

    # 关闭数据库cursor和连接
    def close(self):
        self.cursor.close()
        self.conn.close()

    # 进入with语句自动执行
    def __enter__(self):
        return self
    
    # 退出with语句块自动执行
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()
技术分享图片

 

让对象支持with语句

标签:sql数据库   分享   句柄   self   操作   data   exe   commit   技术分享   

原文地址:https://www.cnblogs.com/yidashi110/p/10091991.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!