使用带有 mysql 连接器 python 的上下文管理器

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(事物)

返回一个上下文管理器,该管理器在块完成后关闭事物。这基本上相当于:

 from contextlib import contextmanager
 
 @contextmanager
 def closing(thing):
     try:
         yield thing
     finally:
         thing.close()
Run Code Online (Sandbox Code Playgroud)

因此,对于您的具体问题,您不仅可以使用连接,还可以使用光标。

你的代码是:

 from contextlib import contextmanager
 
 @contextmanager
 def closing(thing):
     try:
         yield thing
     finally:
         thing.close()
Run Code Online (Sandbox Code Playgroud)


sim*_*0de 3

您必须定义自己的上下文管理器,因为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)