python AttributeError: ‘NoneType’ object has no attribute ‘open’

在写python关闭数据库连接时,代码报错: AttributeError: ‘NoneType’ object has no attribute ‘open’ 。这是因为 connectionfinally 块中可能仍然是 None,而尝试对 None 类型的对象调用 .open 方法会引发此错误。

为了修复这个问题,我们需要更精确地控制 connection 的使用。在 finally 块中,应该确保 connection 既不为 None 也必须是一个有效的连接对象。因此,可以通过检查 connection 是否不为 None 来避免此错误,同时简化 finally 块的处理逻辑。

修改后的正确代码如下:

  def get_charge_electric(self, day, bms_pid_system_code, charge_type):
        connection = None
        cursor = None
        try:
            connection = pymysql.connect(**self.db_config)
            cursor = connection.cursor(pymysql.cursors.DictCursor)

            # 判断charge_type是charge_electric还是discharge_electric,并在query替换
            if charge_type == 'charge_electric':
                query = """
                    SELECT charge_electric 
                    FROM bigdata_test_electric_day 
                    WHERE day = %s AND bms_pid_system_code = %s
                """
            else:
                query = """
                    SELECT discharge_electric
                    FROM bigdata_test_electric_day 
                    WHERE day = %s AND bms_pid_system_code = %s
                """

            cursor.execute(query, (day, bms_pid_system_code))
            result = cursor.fetchone()

            return result[charge_type] if result else None
        except pymysql.MySQLError as e:
            print(f"Error: {e}")
            return None
        finally:
            if cursor is not None:
                cursor.close()
            if connection is not None:
                connection.close()

关注公众号“大模型全栈程序员”回复“小程序”获取1000个小程序打包源码。更多免费资源在http://www.gitweixin.com/?p=2627

发表评论

邮箱地址不会被公开。 必填项已用*标注