AttributeError:'MySQL'对象没有属性'cursor'

问题描述 投票:0回答:2

我正在尝试运行将数据存储在 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()

请帮助修复错误。

谢谢你

python mysql
2个回答
0
投票

你可以将它们包裹在

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

0
投票

导入pymysql

Mysql 类:

def __init__(self, db_host, db_user, db_password, db_database, db_port):
    self.conn = pymysql.connect(
        host=db_host,
        user=db_user,
        password=db_password,
        database=db_database,
        port=db_port,
        )
    self.cursor = self.conn.cursor()
© www.soinside.com 2019 - 2024. All rights reserved.