python - 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()
请帮助修复错误。
谢谢你
解决方案
您可以将它们包装在一个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
推荐阅读
- r - 如何使用 ggplot 的 `geom_tile()` 更改 NA 正方形颜色
- java - 使用 XmlIo 在 apache 梁中读取 xml 文件
- java - 如何从HashMap中提取数据
在改造 2 中? - r - 从另一个数据框中的 a.character 列创建一个数据框,其中包含 R 中的元素列表
- javascript - 如何使用Javascript动态绘制网格框以对齐网格
- matlab - 如何连接电流测量?
- javascript - Angular RxJs Observable 流合并数据
- python - 使用带有多个组的 pandas 提取正则表达式
- php - 如何解析这种格式?
- android - Android 进度指示器在 for 循环中一次递增