使用上下文管理器与mysql连接器python

7

我正在将代码从SQLite数据库迁移到MySQL,但在使用上下文管理器时出现了以下属性错误。

我已尝试使用mydb.cursor() as cursor、mydb:等组合……



mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="",
    database="database_name"

cur = mydb.cursor()


with mydb as cursor:
 AttributeError: __enter__
2个回答

12

如果您创建的对象具有.close()方法,Python有一种内置的实现上下文管理器的方法,可以使用contextlib.closing上下文管理器。

Python文档中获得:

contextlib.closing(thing)

Return a context manager that closes thing upon completion of the block. This is basically equivalent to:

 from contextlib import contextmanager
 
 @contextmanager
 def closing(thing):
     try:
         yield thing
     finally:
         thing.close()

因此,针对您的具体问题,您不仅可以在连接上使用,还可以在游标上使用。

您的代码应该是这样的:

from contextlib import closing

import mysql.connector


query = "SELECT * FROM table"

db_conn_info = {
    "user": "root",
    "passwd": "",
    "host": "localhost",
    "port": 5000,
    "database": "database_name"
}

with closing(mysql.connector.connect(**db_conn_info)) as conn:
    with closing(conn.cursor()) as cur:
        cur.execute(query)
        result = cur.fetchall()


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接