是否可以在 Python 中的 MySQL-Connector 游标和连接上使用“with”关键字?

问题描述

类似于在打开文件时建议使用 with open('myfile','r') as f: 而不是 f=open('myfile','r')'f.close(),我的问题是是否可以对 {{1 Python MysqL 模块中的 }} 和 MysqL.connector.connect() 函数

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

解决方法

你可以使用这个例子

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