Optimizing MySQL JDBC Network Performance with rewriteBatchedStatements=true
The JDBC (Java Database Connectivity) driver offers substantial performance gains via the rewriteBatchedStatements=true
parameter. This setting enables the driver to consolidate multiple database queries into a single network transmission, dramatically reducing network overhead.
MySQL's max_allowed_packet
setting dictates the maximum size of incoming packets. Should a batched query packet exceed this limit, errors can occur. However, the JDBC driver intelligently handles this: it dynamically determines max_allowed_packet
and adjusts its batching strategy to avoid exceeding the limit.
To confirm this behavior, activate the MySQL general log and monitor the JDBC connection. You'll observe Connector/J retrieving max_allowed_packet
and adapting its batching accordingly.
Below is a code example illustrating rewriteBatchedStatements=true
in action:
<code class="language-java">String connectionString = "jdbc:mysql://localhost:3307/mydb?" + "useUnicode=true&characterEncoding=UTF-8" + "&rewriteBatchedStatements=true"; try (Connection con = DriverManager.getConnection(connectionString, "root", "whatever")) { try (PreparedStatement ps = con.prepareStatement("INSERT INTO jdbc (`name`) VALUES (?)")) { for (int i = 1; i <= 1000; i++) { ps.setString(1, "Name" + i); ps.addBatch(); } ps.executeBatch(); } }</code>
Without rewriteBatchedStatements=true
, this code would send individual INSERT
statements. With it enabled, JDBC efficiently bundles these into a single multi-row INSERT
, significantly minimizing network traffic.
Therefore, JDBC ensures efficient batch query handling in MySQL, offering performance enhancements and seamless compatibility without requiring manual developer intervention. The driver intelligently manages batch sizes based on the server's max_allowed_packet
setting.
The above is the detailed content of How Does `rewriteBatchedStatements=true` Optimize MySQL JDBC Network Performance?. For more information, please follow other related articles on the PHP Chinese website!