Java Data Pagination Guide

In Java, manually paginating data is typically done by using the LIMIT and OFFSET keywords in the database query statement. Here is an example code:

// 假设有一个方法用来查询数据库中的数据
public List<Data> fetchData(int pageNumber, int pageSize) {
    int offset = (pageNumber - 1) * pageSize; // 计算偏移量

    String sql = "SELECT * FROM table_name LIMIT ? OFFSET ?";

    try (Connection conn = DriverManager.getConnection(url, username, password);
         PreparedStatement stmt = conn.prepareStatement(sql)) {

        stmt.setInt(1, pageSize);
        stmt.setInt(2, offset);

        ResultSet rs = stmt.executeQuery();

        List<Data> dataList = new ArrayList<>();
        while (rs.next()) {
            Data data = new Data();
            // 从结果集中读取数据并设置到data对象中
            dataList.add(data);
        }

        return dataList;

    } catch (SQLException e) {
        e.printStackTrace();
    }

    return null;
}

In the code above, the pageNumber parameter in the fetchData method represents the page number to be queried, while pageSize represents the number of data entries per page. By using LIMIT and OFFSET in the query statement, the quantity and offset of the query results are restricted to achieve pagination. Finally, the list of query results is returned.

bannerAds