import pymysql
from config import Config
from util.Secret import secret
class DBConnection:
def __init__(self,):
self.host = Config.MYSQL["host"]
self.user = secret.aes_decrypt(Config.MYSQL["user"])
self.password = secret.aes_decrypt(Config.MYSQL["pwd"])
self.db = Config.MYSQL["database"]
self.conn = None
def __enter__(self):
self.conn = pymysql.connect(host=self.host, user=self.user, password=self.password, db=self.db)
self.conn.begin()
return self.conn
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is not None:
self.conn.rollback()
print("rollback")
print(exc_type, exc_val, exc_tb)
else:
self.conn.commit()
print("commit")
self.conn.close()
示例:文章来源:https://www.toymoban.com/news/detail-823209.html
try:
with DBConnection() as conn:
# 执行数据库操作
with conn.cursor() as cur:
cur.execute("select t")
print(cur.fetchall())
except:
pass
"""输出
rollback
<class 'pymysql.err.InternalError'> (1054, "Unknown column 't' in 'field list'") <traceback object at 0x7fd409982ec0>
"""
从上面例子看出,文章来源地址https://www.toymoban.com/news/detail-823209.html
- 在with结构进入时,事务开始begin
- 在with结构退出时,会根据是否产生异常进行commit和rollback操作,并关闭连接
到了这里,关于pymysql 上下文管理器控制事务提交和回滚的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!