MySQL Jdbc驱动的rewriteBatchedStatements参数使batch生效

MySQL Jdbc驱动在默认状况下会无视executeBatch()语句,把咱们指望批量执行的一组sql语句拆散,一条一条地发给MySQL数据库,直接形成较低的性能。mysql

 

只有把rewriteBatchedStatements参数置为true, 驱动才会帮你批量执行SQL (jdbc:mysql://ip:port/db?rewriteBatchedStatements=true)。不过,驱动具体是怎么样批量执行的? 你是否是须要看一下内幕,才敢放心地使用这个选项? 下文会给出答案。sql

 

另外,有人说rewriteBatchedStatements只对INSERT有效,有人说它对UPDATE/DELETE也有效。为此我作了一些实验(详见下文),结论是: 这个选项对INSERT/UPDATE/DELETE都有效,只不过对INSERT它为会预先重排一下SQL语句数据库

注:本文使用的mysql驱动版本是5.1.12ide

实验记录:未打开rewriteBatchedStatements时性能

未打开rewriteBatchedStatements时,根据wireshark嗅探出的mysql报文能够看出,spa

batchDelete(10条记录)  =>  发送10次delete 请求blog

batchUpdate(10条记录)  =>  发送10次update 请求ip

batchInsert(10条记录)  =>  发送10次insert 请求文档

 

也就是说,batchXXX()的确不起做用get

 

实验记录:打开了rewriteBatchedStatements后

打开rewriteBatchedStatements后,根据wireshark嗅探出的mysql报文能够看出

 

batchDelete(10条记录)  =>  发送一次请求,内容为”delete from t where id = 1; delete from t where id = 2; delete from t where id = 3; ….”

batchUpdate(10条记录)  =>  发送一次请求,内容为”update t set … where id = 1; update t set … where id = 2; update t set … where id = 3 …”

batchInsert(10条记录)  =>   发送一次请求,内容为”insert into t (…) values (…) , (…), (…)”

 

对delete和update,驱动所作的事就是把多条sql语句累积起来再一次性发出去;而对于insert,驱动则会把多条sql语句重写成一条风格很酷的sql语句,而后再发出去。 官方文档说,这种insert写法能够提升性能(”This is considerably faster (many times faster in some cases) than using separate single-row INSERT statements”)

 

一个注意事项

须要注意的是,即便rewriteBatchedStatements=true, batchDelete()和batchUpdate()也不必定会走批量: 当batchSize <= 3时,驱动会宁愿一条一条地执行SQL。因此,若是你想验证rewriteBatchedStatements在你的系统里是否已经生效,记得要使用较大的batch.

对应的代码

最后能够看下对应的MySQL  JDBC驱动的代码,以加深印象:

clip_image002[4]

相关文章
相关标签/搜索