Posted on 2009-09-11 10:57
java-flying 阅读(1012)
评论(0) 编辑 收藏
以Oracle 数据库为例:
1.利用游标分页
1public void run() {
2 // 总记录数
3 Integer total = getTotalCount();
4 // 查询最大行数
5 Integer maxCount = 10000;
6 // 总页数
7 Integer totalPage = (total - 1) / maxCount + 1;
8 // 开始行号
9 Integer startNo = 1;
10 String sql = "select m.id from mn00_tbl_music m";
11 Connection conn = null;
12 PreparedStatement stat = null;
13 ResultSet rs = null;
14 try {
15 conn = dataSource.getConnection();
16 // conn.prepareStatement(sql,游标类型,能否更新记录);
17 // 游标类型:
18 // ResultSet.TYPE_FORWORD_ONLY:只进游标
19 // ResultSet.TYPE_SCROLL_INSENSITIVE:可滚动。但是不受其他用户对数据库更改的影响。
20 // ResultSet.TYPE_SCROLL_SENSITIVE:可滚动。当其他用户更改数据库时这个记录也会改变。
21 // 能否更新记录:
22 // ResultSet.CONCUR_READ_ONLY,只读
23 // ResultSet.CONCUR_UPDATABLE,可更新
24 stat = conn.prepareStatement(sql,
25 ResultSet.TYPE_SCROLL_INSENSITIVE,
26 ResultSet.CONCUR_READ_ONLY);
27 rs = stat.executeQuery();
28
29 for (int i = 1; i <= totalPage; i++) {
30 // 将游标移动到指定行
31 //Calling absolute(1) is the same as calling first(). Calling absolute(-1) is the same as calling last().
32 //rs.first()相当于rs.absolute(1)
33 rs.absolute(startNo);
34 // 直接得出该行记录
35 Integer musicId = rs.getInt("id");
36 logger.info(startNo + "-" + musicId + "~~~~~~~~~`~~" + maxCount
37 + "==");
38 startNo += maxCount;
39 }
40 } catch (SQLException e) {
41 logger.error("数据库查询错误!" + e + "," + sql);
42 } finally {
43 DaoUtil.close(conn, stat, rs);
44 }
45 }
2.利用SQL语句分页
1从数据库表中第M条记录开始检索N条记录
2
3 SELECT *
4
5 FROM (SELECT ROWNUM r,t1.* From 表名称 t1 where rownum < M + N) t2
6
7 where t2.r >= M
8
9例如从表Sys_option(主键为sys_id)中从10条记录还是检索20条记录,语句如下:
10
11 SELECT *
12
13 FROM (SELECT ROWNUM R,t1.* From Sys_option where rownum < 30 ) t2
14
15 Where t2.R >= 10
Hibernate 分页