在将上下文管理器添加到Python语言之前,Python DBAPI编写良好。
这样,不同的数据库库就如何实现上下文管理器支持(如果他们完全实现了)做出了 自己的 决定。
通常
,将数据库用作上下文管理器会将您绑定到事务。根据是否存在异常
__enter__,事务从开始于,然后在提交或中止
__exit__。这样,您应该在单独连接后将MySQL连接用作上下文管理器:
connection = util.get_db_connection()with connection as cursor: cursor.execute(...)# connection commit is issued if no exceptions were raised.
该
sqlite3上下文管理器实现是微妙的不同; 它还管理事务,但不从
__enter__方法中返回游标:
con = sqlite3.connect(":memory:")with con: cursor = con.cursor() # or use the connection directly con.execute(...)从技术上讲,它只是
self在上返回
__enter__。



