java数据库分页查询如何实现

17次阅读
没有评论

共计 996 个字符,预计需要花费 3 分钟才能阅读完成。

在 Java 中实现数据库分页查询可以通过使用数据库查询语句的 LIMIT 和 OFFSET 子句来实现。下面是一个示例代码:

public List<Employee> getEmployees(int pageNumber, int pageSize) {
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    List<Employee> employees = new ArrayList<>();

    try {conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");

        String sql = "SELECT * FROM employee LIMIT ? OFFSET ?";
        stmt = conn.prepareStatement(sql);

        int offset = (pageNumber - 1) * pageSize;
        stmt.setInt(1, pageSize);
        stmt.setInt(2, offset);

        rs = stmt.executeQuery();

        while(rs.next()) {Employee employee = new Employee();
            employee.setId(rs.getInt("id"));
            employee.setName(rs.getString("name"));
            employee.setAge(rs.getInt("age"));
            // other columns
            employees.add(employee);
        }
    } catch(SQLException e) {e.printStackTrace();
    } finally {
        try {if(rs != null) rs.close();
            if(stmt != null) stmt.close();
            if(conn != null) conn.close();} catch(SQLException e) {e.printStackTrace();
        }
    }

    return employees;
}

在上面的示例中,我们使用了 LIMIT 和 OFFSET 子句来限制返回的记录数和偏移量,实现了数据库的分页查询。在调用 getEmployees 方法时,指定页码和每页大小即可获取相应的数据。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2024-05-27发表,共计996字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)