MySQLdb使用批量插入executemany方法插入mysql

Posted zoro_robin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MySQLdb使用批量插入executemany方法插入mysql相关的知识,希望对你有一定的参考价值。

python的mysqldb库可以使用批量操作executemany,进行多行插入。

比如向user表(username,salt,pwd)插入数据,具体的sql语句如下:

sql = INSERT INTO 表名 VALUES(%s,%s,%s)  #不管什么类型,统一使用%s作为占位符
param = ((username1, salt1, pwd1), (username2, salt2, pwd2), (username3, salt3, pwd3))  #对应的param是一个tuple或者list
n=cursor.executemany(sql,param)

之前使用execute方法循环写入数据,表字段多的时候,每秒有时只能写入几条,而executemany方法一次性全部提交,1w条数据只用了不到1s,极大提升了性能。

以上是关于MySQLdb使用批量插入executemany方法插入mysql的主要内容,如果未能解决你的问题,请参考以下文章

大量行的 MySQLdb 错误的 executemany

Django cursor.executemany 每个“executemany”的首选批量大小是多少

捕获 cx_Oracle executemany() 批量插入错误“期望数字”

在 Python 中使用 cx_Oracle 中的 executemany() 从批量插入数据加载中查找错误记录

如何在 CrateDB 中使用 python 执行批量插入?

如何使用 executemany 处理异常(MySQL 和 Python)