在代码中添加重连机制,以确保在连接失败时能够重新连接。以下是一个示例代码片段,可以使用这种方法来处理连接失败的情况:
import mysql.connector from mysql.connector import errorcode import time
config = { 'user': 'username', 'password': 'password', 'host': 'database.server.com', 'database': 'database_name', 'raise_on_warnings': True }
def handle_connection_failures(retries=5, wait=5): attempts = 0 conn = None
while attempts < retries:
try:
conn = mysql.connector.connect(**config)
return conn
except mysql.connector.Error as err:
print(f"Error connecting to MYSQL: {err}")
attempts += 1
time.sleep(wait)
# If all retries are exhausted, raise an error
raise Exception("Failed to connect to MYSQL database after multiple attempts")
conn = handle_connection_failures()
cursor = conn.cursor() cursor.execute("SELECT * FROM mytable") results = cursor.fetchall() print(results)
cursor.close() conn.close()