是否可以在 Python 中对 MySQL-Connector 游标和连接使用 "with" 关键字?

Is it possible to use the "with" keyword, in Python, on MySQL-Connector cursors and connections?

类似于打开文件时建议使用 with open('myfile', 'r') as f: 而不是 f=open('myfile', 'r')'f.close(),我的问题是,如果可以对 mysql.connector.connect()<connection>.cursor() 函数在 Python MySQL 模块中。

如果是这样,我应该怎么做? 到目前为止,我一直在使用装饰器来实现相同的结果。

你可以使用这个例子

from mysql.connector import connect

with connect(
    host="localhost",
    user="username",
    password="password",
) as connection:
    with connection.cursor() as cursor:
            cursor.execute("CREATE DATABASE myDB")