我有一个脚本,可以从数据库发出各种读取请求(我有许多类似于read()
方法的方法)。我想避免重复用于创建和关闭游标的代码。所以我在使用上下文管理器和生成器。 (在下面的代码中,db_connection
是一个mysql连接器对象。)
from contextlib import contextmanager
class DatabaseReader():
def __init__(self, db_connection):
self.db_connection = db_connection
self.num = num
@contextmanager
def connect(self):
cursor = self.db_connection.cursor(buffered=True)
try:
yield
finally:
cursor.close()
def read(self):
with self.connect():
cursor.execute("SELECT * FROM table;")
但是,由于未定义AttributeError
,因此调用'read'方法会给我一个cursor
。如何将游标对象“传递”给yield语句?
答案 0 :(得分:3)
在自定义实现中,您需要“屈服” cursor
对象,该对象将绑定在as
语句的with
子句中:
您的代码中需要进行3个修复:
num
传递给self.num = num
cursor
as
语句中添加with
关键字from contextlib import contextmanager
class DatabaseReader():
def __init__(self, db_connection, num):
self.db_connection = db_connection
self.num = num
@contextmanager
def connect(self):
cursor = self.db_connection.cursor(buffered=True)
try:
yield cursor
finally:
cursor.close()
def read(self):
with self.connect() as cur:
cur.execute("SELECT * FROM table;")