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

在mysql连接器python中使用上下文管理器,python,mysql,python-3.x,contextmanager,Python,Mysql,Python 3.x,Contextmanager,我正在将代码从sqlite数据库移动到mysql,而上下文管理器出现问题,出现以下属性错误 我尝试了mydb.cursor和mydb:etc的组合 mydb = mysql.connector.connect( host="localhost", user="root", passwd="", database="database_name" cur = mydb.cursor() 您必须将自己的上下文管理器定义为mysql.connector.connect不是上

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

我尝试了mydb.cursor和mydb:etc的组合



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

cur = mydb.cursor()


您必须将自己的上下文管理器定义为mysql.connector.connect不是上下文管理器。 上下文管理器必须使用uuu enter和uuu exit属性定义。 应该是这样的。使用psycopg2进行测试

DBConnection类: 定义初始自我: self.mydb=mysql.connector.connect host=localhost, 用户=根, passwd=, 数据库=数据库名称 self.cur=self.mydb.cursor 定义u_输入_self: 回归自我 定义退出自身、exc类型、exc val、exc tb: 关闭数据库连接 self.mydb.connection.close
如果要创建的对象具有.close方法,Python可以通过使用contextlib.closing上下文管理器内置实现上下文管理器

从:

contextlib.closingthing 返回一个上下文管理器,该管理器在块完成时关闭对象。 这基本上相当于:

 from contextlib import contextmanager
 
 @contextmanager
 def closing(thing):
     try:
         yield thing
     finally:
         thing.close()
因此,对于您的特定问题,您不仅可以在连接上使用,还可以在光标上使用

您的代码是:

从上下文库导入关闭 导入mysql.connector 查询=从表中选择* 数据库连接信息={ 用户:root, 密码:, 主机:localhost, 港口:5000, 数据库:数据库名称 } 使用closingmysql.connector.connect**db\u conn\u info作为conn: 将closingconn.cursor作为cur: 当前执行 结果=cur.fetchall
 from contextlib import contextmanager
 
 @contextmanager
 def closing(thing):
     try:
         yield thing
     finally:
         thing.close()