使用with语句优化pymysql的操作
一、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操作文件 class A(object): def __init__(self): self.f = None def __enter__(self): print('with语句开始') self.f = open('with测试.txt', encoding='utf8', mode='w') return self.f def __exit__(self, exc_type, exc_val, exc_tb): print('with语句结束') self.f.close() with A() as f: print('IG牛批') f.write('嘿嘿嘿') print('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()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix