Oracle分页查询emp表,已知:pageSize=6,查询第2页。(用java代码实现)
时间: 2024-04-29 12:23:55 浏览: 99
假设emp表结构如下:
| emp_id | emp_name | emp_salary |
| ------ | -------- | ---------- |
| 1 | Tom | 5000 |
| 2 | Jack | 6000 |
| 3 | Lucy | 7000 |
| 4 | Mike | 8000 |
| 5 | Mary | 9000 |
| 6 | John | 10000 |
| 7 | Anna | 11000 |
| 8 | Bob | 12000 |
| 9 | Kate | 13000 |
| 10 | David | 14000 |
Java代码实现:
```java
import java.sql.*;
public class EmpQuery {
public static void main(String[] args) throws SQLException {
int pageSize = 6; // 每页显示记录数
int pageNum = 2; // 查询第2页
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
// 加载数据库驱动
Class.forName("oracle.jdbc.driver.OracleDriver");
// 获取数据库连接
conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "username", "password");
// 构造SQL语句
String sql = "SELECT * FROM (SELECT ROWNUM AS rn, emp_id, emp_name, emp_salary FROM emp) WHERE rn > ? AND rn <= ?";
// 创建PreparedStatement对象
pstmt = conn.prepareStatement(sql);
// 设置参数
int start = (pageNum - 1) * pageSize;
pstmt.setInt(1, start);
pstmt.setInt(2, start + pageSize);
// 执行查询,并返回结果集
rs = pstmt.executeQuery();
// 遍历结果集,输出查询结果
while (rs.next()) {
int empId = rs.getInt("emp_id");
String empName = rs.getString("emp_name");
double empSalary = rs.getDouble("emp_salary");
System.out.println(empId + "\t" + empName + "\t" + empSalary);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 释放资源
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
}
}
}
```
输出结果:
```
7 Anna 11000.0
8 Bob 12000.0
9 Kate 13000.0
10 David 14000.0
```
阅读全文