每天我们都会运行一些 python 3 脚本来将数据填充到我们的应用程序中。 python 脚本在任何地方的 python 上。然后我们使用配额保护(qgtunnel)将数据传输到mysql。数据每天都在变化,在数据较大的日子里,我们经常收到 mysql 错误
pymysql.err.OperationalError: (2013, 'Lost connection to MySQL server during query')
在 mysql 上我们得到
2022-08-17T17:40:39.754094Z 77949 [Note] Aborted connection 77949 to db: 'db' user: 'user' host: 'IP' (Got an error reading communication packets)
这是代码出错的区域。例如,1 个客户将需要创建大约 40,000 条记录。我将它们按 1,000 个进行批处理,然后休眠 6 秒。我还在每个批次后重置数据库连接。但是,我们仍然定期抛出错误,我想知道是否有人有类似的设置并遇到了这个问题。
...
for row in response:
...
sql_query = "insert query"
cursor.execute(sql_query, account_info)
commit_rows = commit_rows + 1
if commit_rows == 1000:
print("committing 1000 records...")
commit_rows = 0
connection.commit()
print("sleeping 6 seconds...")
time.sleep(6.0)
#close and reopen database connection
connection.close()
connection = pymysql.connect(user=os.getenv('mysqluser'),
password=os.getenv('mysqlpwd'),
host=os.getenv('mysqlhost'),
database=os.getenv('mysqldb'))
cursor = connection.cursor()
connection.commit()
这是一些数据库版本(5.7.25)设置...
max_allowed_packet: 1073741824
interactive_timeout: 31536000
wait_timeout: 31536000
connect_timeout: 31536000
编辑:根据@Rick James,我通过使用executemany 得到了消失的错误。这是更新的代码...
...
itemBank = []
for row in response:
...
itemBank.append((myVal1, myVal2...))
commit_rows = commit_rows + 1
if commit_rows == 1000:
print("committing 1000 records...")
commit_rows = 0
cursor.executemany(sql_query, itemBank)
connection.commit()
itemBank = []
print("sleeping 3 seconds...")
time.sleep(3.0)
使用
executemany
以便您可以在单个查询中插入 1000 个。这将运行大约 10 倍的速度(“每秒行数”); 6秒可以缩短。
如果还有问题,将1000降低到100;它仍然会快 10 倍左右。
另请检查
read_buffer_size
的设置。
不要提高空间配置,以免导致交换。因此,请密切关注交换和 OOM。交换对于性能来说非常糟糕,并且可以解释你的错误。
谢谢你