关于JDBC支不支持批量操作,网上的答案各有各的说法,经过一翻测试,发现MySQL驱动JDBC确实不支持批量操作,如果需要其支持批量操作,需要在MySQL的连接url中加上rewriteBatchedStatements=true,加上后,无论MySQL是循环插入还是批量插入,均有改善
测试环境win7 32位系统 mysql5 JDBC驱动为mysql-connector-java-5.1.16-bin.jar,数据库表user为InnorDB
);
conn
(Connection)DriverManager.getConnection(url, userName, password);
conn.setAutoCommit(
false
);
String sql
"
insert into user(username,password) values(?,?)
"
;
PreparedStatement prest
(PreparedStatement)conn.prepareStatement(sql);
long
System.currentTimeMillis();
; x
<
10000
){
prest.setString(
"
username
"
x);
prest.setString(
"
password
"
x);
prest.execute();
}
conn.commit();
long
System.currentTimeMillis();
System.out.println(
"
MySql非批量插入10万条记录用时
"
"
"
);
}
catch
(Exception ex) {
ex.printStackTrace();
}
finally
{
{
(conn
null
)conn.close();
}
catch
(SQLException e) {
e.printStackTrace();
}
}
}
public
static
void
test_mysql_batch(){
String url
"
jdbc:mysql://localhost:3306/test
"
;
String userName
"
root
"
;
String password
"
123456
"
;
Connection conn
null
;
{
Class.forName(
"
com.mysql.jdbc.Driver
"
);
conn
(Connection)DriverManager.getConnection(url, userName, password);
conn.setAutoCommit(
false
);
String sql
"
insert into user(username,password) values(?,?)
"
;
PreparedStatement prest
(PreparedStatement)conn.prepareStatement(sql);
long
System.currentTimeMillis();
; x
<
100000
){
prest.setString(
"
username
"
x);
prest.setString(
"
password
"
x);
prest.addBatch();
}
prest.executeBatch();
conn.commit();
long
System.currentTimeMillis();
System.out.println(
"
MySql批量插入10万条记录用时
"
"
"
);
}
catch
(Exception ex) {
ex.printStackTrace();
}
finally
{
{
(conn
null
)conn.close();
}
catch
(SQLException e) {
e.printStackTrace();
}
}
}
打印结果如下
MySql非批量插入10万条记录用时13712 ms
MySql批量插入10万条记录用时13922 ms
而当MySQL连接参数均加上rewriteBatchedStatements=true时,无论是单条execute执行还是executeBatch执行,均有改善,打印如下
MySql非批量插入10万条记录用时1470 ms
MySql批量插入10万条记录用时1930 ms
这似乎说明,JDBC的批量操作似乎并没有本质上的效率提高,要想其支持批量操作,还是得从MySQL客户端入手
--转自