SQLAlchemy 和 max_allowed_pa​​cket 问题

发布于 2024-09-09 16:00:18 字数 345 浏览 2 评论 0原文

由于我的应用程序的性质,我需要支持将大量数据快速插入数据库。使用executemany() 可以提高性能,但有一个警告。例如,MySQL 有一个名为 max_allowed_pa​​cket 的配置参数,如果我的插入查询的总大小超过其值,MySQL 就会抛出错误。

问题#1:有没有办法告诉 SQLAlchemy 将数据包分割成几个较小的数据包?
问题#2:如果其他 RDBS 也有类似的限制,我应该如何解决这些限制?



PS 我之前已经发布过这个问题,但当我错误地认为我可能不会遇到这个问题时,我删除了它。遗憾的是,事实并非如此。

Due to the nature of my application, I need to support fast inserts of large volumes of data into the database. Using executemany() increases performance, but there's a caveat. For example, MySQL has a configuration parameter called max_allowed_packet, and if the total size of my insert queries exceeds its value, MySQL throws an error.

Question #1: Is there a way to tell SQLAlchemy to split the packet into several smaller ones?
Question #2: If other RDBS have similar constraints, how should I work around them as well?

P.S. I had posted this question earlier but deleted it when I wrongly assumed that likely I will not encounter this problem after all. Sadly, that's not the case.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

带刺的爱情 2024-09-16 16:00:18

我最近遇到了类似的问题,并使用了 - 不是很优雅 - 解决方法:

  • 首先我解析 my.cnf 以获取 max_allow_packets 的值,如果我找不到它,则最大值设置为默认值。
  • 所有数据项都存储在一个列表中。
  • 接下来,对于每个数据项,我计算大约的字节长度(对于字符串,它是字符串的长度(以字节为单位),对于其他数据类型,我采用过去安全的最大字节数。)
  • 我将它们相加,在达到后提交约。 max_allow_packets 的 75%(为了安全起见,SQL 查询也会占用空间)。

这种方法并不是很漂亮,但对我来说却完美无缺。

I had a similar problem recently and used the - not very elegant - work-around:

  • First I parsed my.cnf for a value for max_allow_packets, if I can't find it, the maximum is set to a default value.
  • All data items are stored in a list.
  • Next, for each data item I count the approximate byte length (with strings, it's the length of the string in bytes, for other data types I take the maximum bytes used to be safe.)
  • I add them up, committing after I have reached approx. 75% of max_allow_packets (as SQL queries will take up space as well, just to be on the safe side).

This approach is not really beautiful, but it worked flawlessly for me.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文