我正在使用 Python 中的 MySQLdb 模块与数据库进行交互。我的情况是有一个非常大的列表(数万个元素),我需要将其作为行插入到表中。
我现在的解决方案是生成一个大的 INSERT
语句作为字符串并执行它。
有没有更聪明的方法?
最佳答案
有一个更聪明的方法。
批量插入的问题在于默认情况下 autocommit is enabled从而导致每个 insert
语句在下一次插入开始之前被保存到稳定存储中。
如手册页所述:
By default, MySQL runs with autocommit mode enabled. This means that as soon as you execute a statement that updates (modifies) a table, MySQL stores the update on disk to make it permanent. To disable autocommit mode, use the following statement:
SET autocommit=0;
After disabling autocommit mode by setting the autocommit variable to zero, changes to transaction-safe tables (such as those for InnoDB, BDB, or NDBCLUSTER) are not made permanent immediately. You must use COMMIT to store your changes to disk or ROLLBACK to ignore the changes.
这是 RDBM 系统的一个非常常见的特性,它假定数据库完整性是最重要的。它确实使批量插入每次插入需要 1 秒而不是 1 毫秒。制作过大的插入语句的替代方法试图实现这个单一的提交,有可能使 SQL 解析器过载。
关于Python+MySQL - 批量插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6482004/