温馨提示×

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

小亿
101
2024-05-27 14:29:52
栏目: 编程语言

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

```java

public List getEmployees(int pageNumber, int pageSize) {

Connection conn = null;

PreparedStatement stmt = null;

ResultSet rs = null;

List 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方法时,指定页码和每页大小即可获取相应的数据。

0