我正在将代码从 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__
最佳答案
如果你创建的对象有一个 .close()
方法,Python 有一个内置的方法来实现上下文管理器,通过使用 contextlib.closure
上下文管理器。
来自 Python docs :
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()
关于python - 使用带有 mysql 连接器 python 的上下文管理器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57775507/