OperationalError: 2013 (HY000): Lost connection to MySQL server during query
时间: 2023-11-21 10:55:28 浏览: 125
当执行脚本插入操作时,如果同时操作了太大的数据,比如执行了上千条插入语句,然后再commit一次,这样同时数据量过大,就会造成MySQL连接断开,但是数据还是会插入,不过有可能会丢数据。这种情况下,可以尝试以下解决办法:
1. 增加连接超时时间,可以在连接MySQL时设置connect_timeout参数,例如:conn = pymysql.connect(host='localhost', port=3306, user='root', password='123456', db='test', charset='utf8mb4', connect_timeout=600)
2. 分批次插入数据,可以将上千条插入语句分成多个小批次执行,每次执行完后再commit一次,例如:
```python
import pymysql
conn = pymysql.connect(host='localhost', port=3306, user='root', password='123456', db='test', charset='utf8mb4')
cursor = conn.cursor()
sql_list = ['insert into table1(col1, col2) values(1, "a")', 'insert into table1(col1, col2) values(2, "b")', ...]
batch_size = 1000
for i in range(0, len(sql_list), batch_size):
batch_sql = sql_list[i:i+batch_size]
for sql in batch_sql:
cursor.execute(sql)
conn.commit()
cursor.close()
conn.close()
```
3. 修改MySQL配置文件,增加max_allowed_packet参数的值,例如:max_allowed_packet=256M
阅读全文