我正在使用mysql.connector与mysqldb交互。我在myscript的开头创建了一个数据库连接,并对所有数据库活动(如select/insert/update等)重用同一个连接。我随机得到以下异常,
MySQL连接不可用。
Traceback (most recent call last):
File "database.py", line 46, in query
cursor = self.connection.cursor(buffered=True, dictionary=True)
File "lib/python3.4/site-packages/mysql/connector/connection.py", line 807, in cursor
raise errors.OperationalError("MySQL Connection not available.")
mysql.connector.errors.OperationalError: MySQL Connection not available.
2017-12-08 13:16:03,845 ERROR util.py 1247 MySQL Connection not available.
上述错误的原因是什么?
import mysql.connector
class Database:
"""
Simple Database class
"""
def __init__(self, db_conf, logger):
self.logger = logger
try:
self.connection = mysql.connector.connect(host=db_conf['host'], user=db_conf['user'], password=db_conf['password'],
database=db_conf['db'], port=db_conf['port'])
except Exception as e:
self.logger.exception(e)
raise
def insert_or_update(self, query, type):
"""
Transactional query
"""
try:
cursor = self.connection.cursor(buffered=True)
cursor.execute(query)
self.connection.commit()
if type == 'insert':
last_row_id = cursor.lastrowid
cursor.close()
return last_row_id
elif type == 'update':
row_count = cursor.rowcount
cursor.close()
return row_count
except Exception as e:
self.connection.rollback()
self.logger.info(query)
self.logger.exception(e)
raise
def query(self, query):
"""
Non transactional query
"""
try:
cursor = self.connection.cursor(buffered=True, dictionary=True)
cursor.execute(query)
self.connection.commit()
result = cursor.fetchall()
cursor.close()
return result
except Exception as e:
self.logger.info(query)
self.logger.exception(e)
raise
2条答案
按热度按时间qvsjd97n1#
更多的上下文可能有助于确定此错误的原因,但通常此错误是:
如果是网络错误。然后将您的代码 Package 到except中并重试。如果这是由于会话超时造成的,您应该考虑更好地管理会话,并关闭和重新打开任务的会话。
g6ll5ycj2#
raise errors.OperationalError("MySQL Connection not available.")
在错误中的这条语句意味着连接,当你试图获取数据时,不可用,这可能是由于长wait_timeout
来捕获错误,你可以尝试作为解决方案,我也在寻找一个。that answer will give you brief explaination