gpt4 book ai didi

python - 使用配额保护从 python3 定期获取填充 mysql 的通信数据包读取错误。有什么建议吗?

转载 作者:行者123 更新时间:2023-12-05 05:35:55 25 4
gpt4 key购买 nike

每天我们都会运行一些 python 3 脚本来将数据填充到我们的应用程序中。 python 脚本在任何地方都在 python 上。然后我们使用 quota guard (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。交换对性能来说很糟糕,可能可以解释您的错误。

关于python - 使用配额保护从 python3 定期获取填充 mysql 的通信数据包读取错误。有什么建议吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73393180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com