java写一个分页查询
以下是一个使用Java JDBC和MySQL数据库实现分页查询的示例代码:
public List<Student> getStudents(int pageNumber, int pageSize) {
List<Student> studentList = new ArrayList<>();
int startIndex = (pageNumber - 1) * pageSize;
String sql = "SELECT * FROM students LIMIT ?, ?";
try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "password");
PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setInt(1, startIndex);
statement.setInt(2, pageSize);
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
Student student = new Student();
student.setId(resultSet.getInt("id"));
student.setName(resultSet.getString("name"));
student.setAge(resultSet.getInt("age"));
studentList.add(student);
}
} catch (SQLException e) {
e.printStackTrace();
}
return studentList;
}
在上面的示例中,我们通过传递页数和每页大小来计算起始索引。然后,我们使用LIMIT关键字来限制结果集的大小,并使用PreparedStatement来避免SQL注入攻击。最后,我们将结果集中的每个行转换为Student对象,并将它们添加到列表中返回。
原文地址: http://www.cveoy.top/t/topic/Mlf 著作权归作者所有。请勿转载和采集!