pymysql.err.OperationalError: (2006, “MySQL server has gone away (TimeoutError(110, ‘Connection time

使用python中pymsql库时,当项目程序启动几个小时后,报如下错误:

pymysql.err.OperationalError: (2006, “MySQL server has gone away (TimeoutError(110, ‘Connection timed out’))”)

        这个错误是由于连接超时引起的。可能的原因是MySQL服务器在连接建立后的一段时间内没有活动,导致连接被服务器关闭。

解决方法有两种:

1、增加连接超时时间:

        将connect_timeout参数的值增加到更大的值,例如3600(1小时)。修改连接代码如下:

connection = pymysql.connect(host='host',
                             user='user',
                             connect_timeout=3600,
                             password='passwd',
                             db='db_name',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)

2、检查连接状态和重新连接

        在每次执行数据库查询后,检查连接是否被关闭,并重新连接:在try-except块中添加代码来检查连接状态和重新连接:

try:
    with connection.cursor() as cursor:
        if not connection.open:
            connection.ping(reconnect=True)
        # 进行数据库查询和操作
        query = "select createdDate,rootCause,requestId from db_name;"
        df = pd.read_sql(query, connection)
        print(df)

except pymysql.MySQLError as e:
    print(e)

这样,如果连接超时关闭,代码会在执行查询之前检测到并重新连接到数据库。

猜你喜欢

转载自blog.csdn.net/weixin_44799217/article/details/131468888