【问题标题】:How to implement a context manager for MySql either with MySQL connector or pyMySql如何使用 MySQL 连接器或 pyMySql 为 MySql 实现上下文管理器
【发布时间】:2019-12-28 05:12:15
【问题描述】:

尝试为 MySql 连接实现上下文管理器时收到一条错误消息。

我使用了 MySql.connector 模块,包括连接数据库的连接选项和 pyMySql 模块,总是得到相同的结果。

import pymysql

class MySQLConnector:
    def __init__(self, con_dict):
        self.cnx = None
        self.con_dict = con_dict

    def __enter__(self):
        self.cnx = pymysql.connect(**self.con_dict)
        return self.cnx

    def __exit__(self):
        self.cnx.close()

class ReceiveBroke(QDialog):           

    def __init__(self, db, config):    
        super().__init__()             
        with MySQLConnector(config) as 
            cur = self.cnx.cnx.cursor()
            qry = "SELECT * FROM horses
            cur.execute(qry)           
            result = cur.fetchall()    
            print(result)              
            self.setUI()               
            self.conTest()

    def conTest(self): 
        if self.cnx.ope
            print("y")              

我希望获得一个工作上下文管理器关闭数据库连接一个完成with Block。 结果:错误消息。总是在执行“with”块中的最后一行之后:“TypeError exit 采用一个位置参数,但给出了四个”,此时程序崩溃。

【问题讨论】:

    标签: mysql python-3.x pymysql


    【解决方案1】:

    希望您已经发现了错误。如果不是,我认为错误信息很清楚:

    TypeError exit takes one positional argument but four were given
    

    __exit__ 函数需要 4 个参数:self、type、value、traceback。最后 3 个与 with 块中可能发生的任何异常有关。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-30
      • 1970-01-01
      • 2011-09-17
      • 2021-11-16
      • 2020-09-30
      • 2012-09-30
      • 2015-11-03
      • 2011-02-25
      相关资源
      最近更新 更多