java 实现 oracle 分页查询
时间: 2023-10-19 13:21:13 浏览: 78
下面是一个简单的 Java 实现 Oracle 分页查询的示例代码:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class OraclePaginationExample {
private static final String DB_URL = "jdbc:oracle:thin:@localhost:1521:xe";
private static final String DB_USERNAME = "username";
private static final String DB_PASSWORD = "password";
public static void main(String[] args) {
int page = 2; // 查询第二页数据
int pageSize = 10; // 每页显示10条数据
int start = (page - 1) * pageSize + 1;
int end = page * pageSize;
try {
Connection conn = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
PreparedStatement stmt = conn.prepareStatement(
"SELECT * FROM (SELECT ROWNUM RN, T.* FROM (SELECT * FROM my_table ORDER BY id) T WHERE ROWNUM <= ?) WHERE RN >= ?");
stmt.setInt(1, end);
stmt.setInt(2, start);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
// 其他字段...
System.out.println(id + ", " + name);
}
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
在上面的示例代码中,我们首先定义了要查询的页码和每页显示的条数,然后计算出查询的起始行和结束行。我们使用了 Oracle 的 ROWNUM 关键字来实现分页查询,将所有的数据按照指定的排序方式查询出来,然后再通过 ROWNUM 进行筛选。最后,我们将查询结果遍历输出即可。
阅读全文