立即抛出 sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2013, '在查询期间丢失与 MySQL 服务器的连接')

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

我遇到了一个非常奇怪的问题,在循环中使用 db.session.execute('insert into table_a select * from table_b where xxx') 语句时,我在测试数据的固定点始终收到以下异常。

sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2013, 'Lost connection to MySQL server during query')

我相信这与连接计数或超时设置无关。由于join操作较大,执行150次循环大约需要5秒,并且每次都恰好在第150次迭代时发生异常。这在 Java 中非常快,并且对于相同的逻辑和相同的 MySQL 来说从来都不是问题。而且总数据量很小,大约只有5000行,不到300KB。

在Python中,我在每次迭代结束时执行db.session.commit()。但没有任何帮助。

到达第 150 次迭代时立即抛出连接丢失异常,我不确定是什么原因导致的。

这是测试代码:

        normal_date_pattern = '%Y-%m-%d'
        day_start_hour_format_pattern = '%Y-%m-%d %H:00:00'
        day_end_hour_format_pattern = '%Y-%m-%d %H:59:59'

        while actual_end_time > start_time:
            start_current_hour_str = start_time.strftime(self.day_start_hour_format_pattern)
            end_current_hour_str = start_time.strftime(self.day_end_hour_format_pattern)
            # log when meet 0'oclock
            if start_current_hour_str.endswith('00:00:00'):
                current_app.logger.info(f'processing date {start_time.strftime(self.normal_date_pattern)}')
            # insert into db
            db.session.execute(
                text(
                    """
                        INSERT INTO table_1
                        SELECT * FROM table_2
                        WHERE table_2.start_time>=:start_time
                        AND table_2.end_time<=:end_time
                        ON DUPLICATE KEY UPDATE
                            snapshot_date = snapshot_date,
                            snapshot_date_loc = VALUES(snapshot_date_loc)
                    """
                ),
                params={
                    'start_time': start_current_hour_str,
                    'end_time': end_current_hour_str
                }
            )
            db.session.commit()

            # add one hour to process next hour
            start_time = start_time + timedelta(hours=1)

此代码在 Flask 应用程序中运行,但即使我将其提取到单独的脚本并使用单独的引擎和 sessionmaker,它也会像往常一样崩溃并出现相同的错误。

python mysql flask flask-sqlalchemy
1个回答
0
投票

这是MySQL服务器版本的问题,与代码无关。MySQL版本太旧,不支持我的代码。这是原因和解决方案,只要更新我的MySQL版本,就没有问题了。看到这个问题

© www.soinside.com 2019 - 2024. All rights reserved.