如果要限制查询的结果,可以使用Statement.setMaxRows(int max)方法调用。此调用将允许ResultSet对象包含在setMaxRows方法的参数中指定的最大记录数。
限制查询中返回的数据数量的另一种方法是使用特定于数据库的命令,例如MySQLlimit命令。
package org.nhooo.example.jdbc; import java.sql.*; public class SetMaxRowExample { 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(); // 执行SQL查询以获取数据总数 // 在产品表中。 String query = "select count(*) from products"; ResultSet rs = statement.executeQuery(query); while (rs.next()) { System.out.println("Total Products: " + rs.getInt(1)); } // 设置可以存储在 // 结果集。 statement.setMaxRows(5); // 执行SQL查询以从产品中检索数据 // 表。 query = "select id, code, name, price from products"; rs = statement.executeQuery(query); System.out.println("Data read after the MaxRows is set."); while (rs.next()) { System.out.println("ID: " + rs.getInt("id") + ", CODE: " + rs.getString("code") + ", NAME: " + rs.getString("name") + ", PRICE: " + rs.getBigDecimal("price")); } } catch (SQLException e) { e.printStackTrace(); } } }
运行代码时,我们将看到从Products表中仅读取了5条记录,而不是10条记录。这是在Statement对象中设置最大行数的结果。
以下是我们代码的输出。
Total Products: 9 Data read after the MaxRows is set. 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
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>