MySQL和JDBC与rewriteBatchedStatements = true

我一直在阅读, 在这里 , 这里和这里关于使用rewriteBatchedStatements=true的优势

如果我理解正确,那么在rewriteBatchedStatements=true的情况下,JDBC将尽可能多的查询包装到单个networking数据包中,从而降低networking开销。 我对吗?

然后引起我的注意,在MySQL服务器中为max_allowed_packet定义的值可能会导致查询问题(查询不在服务器上执行)。

所以我的第二个问题是,JDBC是否知道分配给max_allowed_packet的值,并因此使数据包小于max_allowed_packet的定义值,或者这是开发人员必须考虑的事情?

如果我了解错误,请让我知道。

在rewriteBatchedStatements = true的情况下,JDBC将尽可能多的查询包装到单个networking数据包中,从而降低networking开销。 我对吗?

是。 下面的代码

 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(); } } 

即使我创build了批处理,也会发送单独的INSERT语句

 INSERT INTO jdbc (`name`) VALUES ('Line 1: Lorem ipsum ...') INSERT INTO jdbc (`name`) VALUES ('Line 2: Lorem ipsum ...') 

但是,如果我将连接string更改为包含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_pa​​cket的值,并因此使数据包小于max_allowed_pa​​cket定义的值…?

是。 如果启用MySQL通用日志并检查它,您会看到MySQL Connector / J在连接时会检查一堆variables,其中一个是max_allowed_packet 。 您还可以设置一个小的max_allowed_packet值,并validation如果整个批处理的单个语句将超过max_allowed_packet ,则JDBC会将批次拆分为多个多行INSERT语句。