繁体   English   中英

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

[英]Using a context manager with mysql connector python

我正在将我的代码从 sqlite 数据库移动到 mysql,但上下文管理器出现问题,出现以下属性错误。

我试过将 mydb.cursor() 组合为游标,mydb: 等...



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

cur = mydb.cursor()

with mydb as cursor:
 AttributeError: __enter__

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

如果您正在创建的对象有一个.close()方法,Python 有一个内置的方法来实现一个上下文管理器,通过使用contextlib.closing上下文管理器。

来自Python 文档

contextlib.closure(东西)

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM