使用rewriteBatchedStatements=true,JDBC将尽可能多的查询打包到一个网络数据包中,从而降低网络开销.我说得对吗?
对下面的代码
String myConnectionString =
"jdbc:mysql://localhost:3307/mydb?" +
"useUnicode=true&characterEncoding=UTF-8";
try (Connection con = DriverManager.getConnection(myConnectionString, "root", "whatever")) {
try (PreparedStatement ps = con.prepareStatement("INSERT INTO jdbc (`name`) VALUES (?)")) {
for (int i = 1; i <= 5; i++) {
ps.setString(1, String.format(
"Line %d: Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
i));
ps.addBatch();
}
ps.executeBatch();
}
}
即使我已经创建了一个批,也会发送单独的INSERT语句
INSERT INTO jdbc (`name`) VALUES ('Line 1: Lorem ipsum ...')
INSERT INTO jdbc (`name`) VALUES ('Line 2: Lorem ipsum ...')
但是,如果我将连接字符串更改为包含rewriteBatchedStatements=true
String myConnectionString =
"jdbc:mysql://localhost:3307/mydb?" +
"useUnicode=true&characterEncoding=UTF-8" +
"&rewriteBatchedStatements=true";
然后JDBC将发送一个或多个多行INSERT语句
INSERT INTO jdbc (`name`) VALUES ('Line 1: Lorem ipsum ...'),('Line 2: Lorem ipsum ...')
JDBC是否知道分配给max_allowed_数据包的值,从而使数据包小于为max_allowed_数据包定义的值?
对如果您启用MySQL常规日志(log)并判断它,您将看到MySQL Connector/J在连接时判断一组变量,其中一个是max_allowed_packet
.您还可以设置一个小的max_allowed_packet
值,并验证JDBC是否将一个批拆分为多个多行INSERT语句(如果整个批的单个此类语句将超过max_allowed_packet
).