Cal*_*lum 7 python mysql contextmanager python-3.x
我正在将代码从 sqlite 数据库移动到 mysql,并且上下文管理器出现问题,出现以下属性错误。
我尝试过 mydb.cursor() 作为光标、mydb: 等的组合...
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
database="database_name"
cur = mydb.cursor()
Run Code Online (Sandbox Code Playgroud)
with mydb as cursor:
AttributeError: __enter__
Run Code Online (Sandbox Code Playgroud)
Dan*_*ima 12
如果您创建的对象具有方法.close()
,则 Python 有一种内置方法可以通过使用contextlib.closing
上下文管理器来实现上下文管理器。
来自Python文档:
contextlib.close(事物)
返回一个上下文管理器,该管理器在块完成后关闭事物。这基本上相当于:
Run Code Online (Sandbox Code Playgroud)from contextlib import contextmanager @contextmanager def closing(thing): try: yield thing finally: thing.close()
因此,对于您的具体问题,您不仅可以使用连接,还可以使用光标。
你的代码是:
from contextlib import contextmanager
@contextmanager
def closing(thing):
try:
yield thing
finally:
thing.close()
Run Code Online (Sandbox Code Playgroud)
您必须定义自己的上下文管理器,因为mysql.connector.connect
它不是上下文管理器。上下文管理器必须使用__enter__
和__exit__
属性来定义。应该是这样的。(测试使用psycopg2
)
class DBConnection:
def __init__(self):
self.mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
database="database_name"
)
self.cur = self.mydb.cursor()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
# close db connection
self.mydb.connection.close()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7350 次 |
最近记录: |