首页 > 解决方案 > AttributeError:“MySQL”对象没有属性“光标”

问题描述

我正在尝试运行将数据存储在 MySQL 数据库中的 Python 脚本。

运行脚本时出现此错误

File "/root/bot/airdrop-bot/modules/core/mysql.py", line 19, in __del__
    self.cursor.close()
AttributeError: 'MySQL' object has no attribute 'cursor'

import mysql.connector

from system import config


class MySQL:
    """Do not touch this class unless you really know what your doing."""
    def __init__(self):
        self.connection = mysql.connector.connect(
            host=config.MYSQL_HOST,
            database=config.MYSQL_DATABASE,
            user=config.MYSQL_USERNAME,
            passwd=config.MYSQL_PASSWORD,
            charset="utf8mb4"
        )
        self.cursor = self.connection.cursor(dictionary=True)

    def __del__(self):
        self.cursor.close()
        self.connection.close()

    def execute(self, query, binds=(), get_last_row_id=False):
        self.cursor.execute(query, binds)
        self.connection.commit()
        if get_last_row_id:
            return self.cursor.lastrowid
        else:
            return self.cursor.rowcount

    def fetchall(self, query, binds=()):
        self.cursor.execute(query, binds)
        return self.cursor.fetchall()

    def fetchone(self, query, binds=()):
        self.cursor.execute(query, binds)
        return self.cursor.fetchone()

请帮助修复错误。

谢谢你

标签: pythonmysql

解决方案


您可以将它们包装在一个try/except块中:

def __del__(self):
    for obj in (self.cursor, self.connection):
        try:
            obj.close()
        except:
            # continue silently!
            pass

对于您尚未创建连接和/或游标的情况,您可以使其更加动态:

def __del__(self):
    for obj in ("cursor", "connection"):
        if hasattr(self, obj):
            try:
                getattr(self, obj).close()
            except:
                pass

推荐阅读