提取大小是在单次数据库网络行程中应从数据库中提取的行数,当需要更多行时,应用程序会将另一个请求发送到数据库服务器。
设置正确的提取大小将有助于我们的程序在程序与数据库服务器之间生成的网络通信数量方面表现良好。
package org.nhooo.example.jdbc; import java.sql.DriverManager; import java.sql.Connection; import java.sql.Statement; import java.sql.ResultSet; import java.sql.SQLException; public class SetFetchSizeExample { private static final String URL = "jdbc:mysql://localhost/nhooo"; private static final String USERNAME = "root"; private static final String PASSWORD = ""; public static void main(String[] args) { try (Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD)) { Statement statement = connection.createStatement(); // 将提取大小设置为100。 statement.setFetchSize(100); // 执行给定的SQL查询 String q = "select id, code, name, price from products"; ResultSet rs = statement.executeQuery(q); while (rs.next()) { System.out.println("id:" + rs.getLong("id") + ", code:" + rs.getString("code") + ", name:" + rs.getString("name") + ", price:" + rs.getString("price")); } } catch (SQLException e) { e.printStackTrace(); } } }
上面的代码片段的示例结果是:
id:1, code:P0000001, name:UML Distilled 3rd Edition, price:25.00 id:3, code:P0000003, name:PHP Programming, price:20.00 id:4, code:P0000004, name:Longman Active Study Dictionary, price:40.00 id:5, code:P0000005, name:Ruby on Rails, price:24.00 id:6, code:P0000006, name:Championship Manager, price:0.00 id:7, code:P0000007, name:Transport Tycoon Deluxe, price:0.00 id:8, code:P0000008, name:Roller Coaster Tycoon 3, price:0.00 id:9, code:P0000009, name:Pro Evolution Soccer, price:0.00 id:10, code:P0000010, name:Data Structures, Algorithms, price:50.99
Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=mysql/mysql-connector-java/8.0.17/mysql-connector-java-8.0.17.jar --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.17</version> </dependency>