背景
一直以为python库MySQLdb
批量执行函数executeMany
有做sql拼接的优化,实际使用过程中发现,自己拼接的批量执行sql网络耗时要比使用executeMany
少很多,特此记录。
官方说明
MySQLdb
依赖官方的mysql客户端,官方文档里有下面一段话:
In most cases, the executemany() method iterates through the sequence of parameters, each time passing the current parameters to the execute() method.
大部分情况下,executemany
就是execute
的循环执行。
测试
用tcpdump
做抓包测试
tcpdump dst host $MysqlServerHost
执行python脚本
import random
import string
db = connect('dev_frps')
sql = '''insert into black_address (address, coin, created_at)
values (%s, %s, now())'''
args = [
(''.join(random.choices(string.ascii_letters, k=31)), 'btc'),
(''.join(random.choices(string.ascii_letters, k=31)), 'btc'),
]
db.executeMany(sql, args)
db.commit()
我们可以看到插入2条数据,会发送两个数据包
import random
import string
db = connect('dev_frps')
sql = '''insert into black_address (address, coin, created_at)
values (%s, %s, now()), (%s, %s, now())'''
args = [
''.join(random.choices(string.ascii_letters, k=31)), 'btc',
''.join(random.choices(string.ascii_letters, k=31)), 'btc'
]
db.execute(sql, args)
db.commit()
当我们使用批量插入时,只发送一次数据包