mysql分页 与jdbc分页

Java分页代码的实现

您的评价:
     

在项目中,分页是一个项目中必不可少的,它可以防止我们从数据库中进行大量数据查询时速度变慢,提高我们的查询效率

1、定义分页模型:PageModel

001packagecom.common.page; 
002   
003importjava.util.List; 
004   
005/**
006 * 封装分页信息
007 * @author Administrator
008 *
009 */ 
010publicclass PageModel<E> { 
011   
012    //结果集 
013    privateList<E> list; 
014       
015    //查询记录数 
016    privateint totalRecords; 
017       
018    //每页多少条数据 
019    privateint pageSize; 
020       
021    //第几页 
022    privateint pageNo; 
023       
024    /**
025     * 总页数
026     * @return
027     */ 
028    publicint getTotalPages() { 
029        return(totalRecords + pageSize - 1) / pageSize; 
030    
031       
032    /**
033     * 取得首页
034     * @return
035     */ 
036    publicint getTopPageNo() { 
037        return1
038    
039       
040    /**
041     * 上一页
042     * @return
043     */ 
044    publicint getPreviousPageNo() { 
045        if(pageNo <= 1) { 
046            return1
047        
048        returnpageNo - 1
049    
050       
051    /**
052     * 下一页
053     * @return
054     */ 
055    publicint getNextPageNo() { 
056        if(pageNo >= getBottomPageNo()) { 
057            returngetBottomPageNo(); 
058        
059        returnpageNo + 1;   
060    
061       
062    /**
063     * 取得尾页
064     * @return
065     */ 
066    publicint getBottomPageNo() { 
067        returngetTotalPages(); 
068    
069       
070    publicList<E> getList() { 
071        returnlist; 
072    
073   
074    publicvoid setList(List<E> list) { 
075        this.list = list; 
076    
077   
078    publicint getTotalRecords() { 
079        returntotalRecords; 
080    
081   
082    publicvoid setTotalRecords(inttotalRecords) { 
083        this.totalRecords = totalRecords; 
084    
085   
086    publicint getPageSize() { 
087        returnpageSize; 
088    
089   
090    publicvoid setPageSize(intpageSize) { 
091        this.pageSize = pageSize; 
092    
093   
094    publicint getPageNo() { 
095        returnpageNo; 
096    
097   
098    publicvoid setPageNo(intpageNo) { 
099        this.pageNo = pageNo; 
100    
101}
2、分页测试:在MySQL中建立admin表,里面有字段id、name、password

3、简历Admin的实体bean类:

01packagecom.common.page; 
02   
03publicclass Admin { 
04    privateint id; 
05    privateString name; 
06    privateString password; 
07    publicint getId() { 
08        returnid; 
09    
10    publicvoid setId(intid) { 
11        this.id = id; 
12    
13    publicString getName() { 
14        returnname; 
15    
16    publicvoid setName(String name) { 
17        this.name = name; 
18    
19    publicString getPassword() { 
20        returnpassword; 
21    
22    publicvoid setPassword(String password) { 
23        this.password = password; 
24    
25   
26}
4、测试调用:
01packagecom.common.page; 
02   
03importjava.sql.Connection; 
04importjava.sql.PreparedStatement; 
05importjava.sql.ResultSet; 
06importjava.sql.SQLException; 
07importjava.util.ArrayList; 
08importjava.util.List; 
09   
10importcom.common.db.DbUtil; 
11   
12publicclass Client { 
13    publicstatic PageModel findAdmins(intpageNo,int pageSize){ 
14        Connection conn=DbUtil.getConnection(); 
15        String sql="select * from admin limit ?,?"
16        PageModel pageModel=null
17        PreparedStatement pstm=null
18        ResultSet rs=null
19        Admin admin=null
20        List<Admin> list=newArrayList<Admin>(); 
21        try
22            pstm=conn.prepareStatement(sql); 
23            pstm.setInt(1, (pageNo-1)*pageSize); 
24            pstm.setInt(2, pageNo*pageSize); 
25            rs=pstm.executeQuery();; 
26            while(rs.next()){ 
27                admin=newAdmin(); 
28                admin.setId(rs.getInt("a_id")); 
29                admin.setName(rs.getString("a_name")); 
30                admin.setPassword(rs.getString("a_pwd")); 
31                list.add(admin); 
32            
33            ResultSet rs2=pstm.executeQuery("select count(*) from admin"); 
34            inttotal=0
35            if(rs2.next()){ 
36                total=rs2.getInt(1); 
37            
38            pageModel=newPageModel(); 
39            pageModel.setPageNo(pageNo); 
40            pageModel.setPageSize(pageSize); 
41            pageModel.setTotalRecords(total); 
42            pageModel.setList(list); 
43        }catch (SQLException e) { 
44            e.printStackTrace(); 
45        }finally
46            DbUtil.close(conn); 
47            DbUtil.close(pstm); 
48            DbUtil.close(rs); 
49        
50        returnpageModel; 
51    
52       
53    publicstatic void main(String[] args) { 
54        PageModel pageModel=Client.findAdmins(2,4); 
55        List<Admin> list=pageModel.getList(); 
56        for(Admin a:list){ 
57            System.out.print("ID:"+a.getId()+",用户名:"+a.getName()+",密码:"+a.getPassword()); 
58            System.out.println(); 
59        
60        System.out.print("当前页:"+pageModel.getPageNo()+" "); 
61        System.out.print("共"+pageModel.getTotalPages()+"页  "); 
62        System.out.print("首页:"+pageModel.getTopPageNo()+" "); 
63        System.out.print("上一页:"+pageModel.getPreviousPageNo()+" "); 
64        System.out.print("下一页:"+pageModel.getNextPageNo()+" "); 
65        System.out.print("尾页:"+pageModel.getBottomPageNo()+" "); 
66        System.out.print("共"+pageModel.getTotalRecords()+"条记录"); 
67        System.out.println(); 
68    
69   
70}
这样分页效果就实现了,我们要实现分页效果,只要传入相应的参数和相应的数据库执行语句即可实现,希望大家能灵活运用。

转自:http://blog.csdn.net/harderxin/article/details/7731313



jdbc demo 分页

JDBC分页工具类

您的评价:
     

不知道大家做项目做到最后有什么感觉没有,其实大家做来做去就是做一个列表加上分页和多条件的查询,只是不同的项目业务流程不一样而已,所以今天我想说说这里的分页。

1、 大家需要了解的是为什么我们需要分页?

因为当数据量太大时,会影响查询和传输的性能,并且我们从用户角度来考虑的话,如果让用户一次性看到成千上万条记录那用户也会疯掉的。

2、 对我们来说有哪些可实现的分页技术?

a、 存储过程分页,即在数据库中创建一个存储过程,传入SQL和页码获取当前页的记录,这个需要大家对存储过程有比较好的认识(我这块不行),当然这个从性能上来说是最好的,但是不能跨数据库平台。

b、 使用数据库专有SQL语句进行分页(Oracle的rownum、MSSQL的top、MySql的limit等),性能也很好,但是还是不能跨数据库(其实真实项目中没那么多项目要求都跨数据库)。

c、 JDBC分页,通过Statement的statement.setMaxRow(endIndex)和resultSet.absoulte(beginIndex)取得当前页范围内的记录。此种方式的性能依赖于厂商对JDBC规范的实现。这种方式的通用性是最好的,性能也不错,完全与数据库平台无关了。

d、 根据数据库类型自动生成数据库专有特性的sql语句,其实说白了也就是Hibernate的实现方式,这个自己也写过一个,其实就是根据数据库类型生成不同的数据库SQL专有语句而已。

 

下面我们需要写一个分页工具类,在写之前我们需要弄明白分页的原理。为了能够取得指定页码所对应的记录,我们是不是需要两个关键的参数:总记录数和每页的记录数;

每页的记录数我们可以设置一个默认值,10、15、20、25都无所谓,根据实际需求。

总记录数就没办法了,需要额外从数据库中利用Count函数取了,通过这两个参数我们是不是可以计算出总页数。同时我们也可以判断用户传过来的页码是否有效(小于第一页OR超出最后一页),然后我们再根据页码和每页记录数是不是就可以计算出当前页的的开始条数和终止条数了。

 

下面我们就需要来看看分页的工具类了

001package com.iflytek.page;
002
003/**
004 * 分页工具类
005 *
006 * @author xudongwang 2012-1-19
007 *
008 *         Email:xdwangiflytek@gmail.com
009 */
010public class Page {
011
012    /**
013     * 总记录数
014     */
015    private int totalRow;
016
017    /**
018     * 每页记录数
019     */
020    private int pageSize = 10;
021
022    /**
023     * 当前页码
024     */
025    private int currentCount;
026
027    /**
028     * 总页数
029     */
030    private int total;
031
032    /**
033     * 起始记录下标
034     */
035    private int beginIndex;
036
037    /**
038     * 截止记录下标
039     */
040    private int endIndex;
041
042    /**
043     * 构造方法,使用总记录数,当前页码
044     *
045     * @param totalRow
046     *            总记录数
047     * @param currentCount
048     *            当前页面,从1开始
049     */
050    public Page(int totalRow, int currentCount) {
051        this.totalRow = totalRow;
052        this.currentCount = currentCount;
053        calculate();
054    }
055
056    /**
057     * 构造方法 ,利用总记录数,当前页面
058     *
059     * @param totalRow
060     *            总记录数
061     * @param currentCount
062     *            当前页面
063     * @param pageSize
064     *            默认10条
065     */
066    public Page(int totalRow, int currentCount, int pageSize) {
067        this.totalRow = totalRow;
068        this.currentCount = currentCount;
069        this.pageSize = pageSize;
070        calculate();
071    }
072
073    private void calculate() {
074        total = totalRow / pageSize + ((totalRow % pageSize) > 0 ? 1 : 0);
075
076        if (currentCount > total) {
077            currentCount = total;
078        } else if (currentCount < 1) {
079            currentCount = 1;
080        }
081
082        beginIndex = (currentCount - 1) * pageSize;
083        endIndex = beginIndex + pageSize;
084        if (endIndex > totalRow) {
085            endIndex = totalRow;
086        }
087    }
088
089    public int getTotalRow() {
090        return totalRow;
091    }
092
093    public int getPageSize() {
094        return pageSize;
095    }
096
097    public int getCurrentCount() {
098        return currentCount;
099    }
100
101    public int getTotal() {
102        return total;
103    }
104
105    public int getBeginIndex() {
106        return beginIndex;
107    }
108
109    public int getEndIndex() {
110        return endIndex;
111    }
112
113}

 继续

在后台获取前台传进来的页码 //从页面取得页码

1int currentPage = 1
2try
3    currentPage = Integer.parseInt(request.getParameter("currentPage")); 
4} catch (Exception ex) {} 
5   
6//取得总记录数,创建Page对象 
7int totalRow = studentDao.getAllStudents();//通过select count 取得总记录数 
8Page page = new Page(totalRow, currentPage); 
9studentDao.list(page);
数据访问层, StduentDao.java
01public List<Stduent> getStudentsByPage(Page page) { 
02        List<Stduent> students = new ArrayList<Stduent>(); 
03        try
04            String sql = "SELECT id,name,email FROM tbl_stduent"
05            Connection conn = null
06            try
07                conn = DbUtil.getConnection(); 
08                Statement statement = conn.createStatement(); 
09                statement.setMaxRows(page.getEndIndex());//关键代码,设置最大记录数为当前页记录的截止下标 
10                ResultSet resultSet = statement.executeQuery(sql); 
11                if (page.getBeginIndex() > 0) { 
12                    resultSet.absolute(page.getBeginIndex());//关键代码,直接移动游标为当前页起始记录处 
13                
14                while (resultSet.next()) { 
15                    Stduent student = new Student(); 
16                    …… 
17                    students.add(student); 
18                
19                resultSet.close(); 
20                statement.close(); 
21            } finally
22                if (conn != null) { 
23                    conn.close(); 
24                
25            
26        } catch (SQLException e) { 
27            e.printStackTrace(); 
28        
29        return students; 
30    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值