`
bdk82924
  • 浏览: 552402 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

JDBC分页工具类

 
阅读更多

转自:http://xdwangiflytek.iteye.com/blog/1358080

 

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

 

 

---

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

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

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

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

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

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

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

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

 

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

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

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

 

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

Java代码 复制代码 收藏代码
  1. package com.iflytek.page;   
  2.   
  3. /**  
  4.  * 分页工具类  
  5.  *   
  6.  * @author xudongwang 2012-1-19  
  7.  *   
  8.  *         Email:xdwangiflytek@gmail.com  
  9.  */  
  10. public class Page {   
  11.   
  12.     /**  
  13.      * 总记录数  
  14.      */  
  15.     private int totalRow;   
  16.   
  17.     /**  
  18.      * 每页记录数  
  19.      */  
  20.     private int pageSize = 10;   
  21.   
  22.     /**  
  23.      * 当前页码  
  24.      */  
  25.     private int currentCount;   
  26.   
  27.     /**  
  28.      * 总页数  
  29.      */  
  30.     private int total;   
  31.   
  32.     /**  
  33.      * 起始记录下标  
  34.      */  
  35.     private int beginIndex;   
  36.   
  37.     /**  
  38.      * 截止记录下标  
  39.      */  
  40.     private int endIndex;   
  41.   
  42.     /**  
  43.      * 构造方法,使用总记录数,当前页码  
  44.      *   
  45.      * @param totalRow  
  46.      *            总记录数  
  47.      * @param currentCount  
  48.      *            当前页面,从1开始  
  49.      */  
  50.     public Page(int totalRow, int currentCount) {   
  51.         this.totalRow = totalRow;   
  52.         this.currentCount = currentCount;   
  53.         calculate();   
  54.     }   
  55.   
  56.     /**  
  57.      * 构造方法 ,利用总记录数,当前页面  
  58.      *   
  59.      * @param totalRow  
  60.      *            总记录数  
  61.      * @param currentCount  
  62.      *            当前页面  
  63.      * @param pageSize  
  64.      *            默认10条  
  65.      */  
  66.     public Page(int totalRow, int currentCount, int pageSize) {   
  67.         this.totalRow = totalRow;   
  68.         this.currentCount = currentCount;   
  69.         this.pageSize = pageSize;   
  70.         calculate();   
  71.     }   
  72.   
  73.     private void calculate() {   
  74.         total = totalRow / pageSize + ((totalRow % pageSize) > 0 ? 1 : 0);   
  75.   
  76.         if (currentCount > total) {   
  77.             currentCount = total;   
  78.         } else if (currentCount < 1) {   
  79.             currentCount = 1;   
  80.         }   
  81.   
  82.         beginIndex = (currentCount - 1) * pageSize;   
  83.         endIndex = beginIndex + pageSize;   
  84.         if (endIndex > totalRow) {   
  85.             endIndex = totalRow;   
  86.         }   
  87.     }   
  88.   
  89.     public int getTotalRow() {   
  90.         return totalRow;   
  91.     }   
  92.   
  93.     public int getPageSize() {   
  94.         return pageSize;   
  95.     }   
  96.   
  97.     public int getCurrentCount() {   
  98.         return currentCount;   
  99.     }   
  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. }  
package com.iflytek.page;

/**
 * 分页工具类
 * 
 * @author xudongwang 2012-1-19
 * 
 *         Email:xdwangiflytek@gmail.com
 */
public class Page {

	/**
	 * 总记录数
	 */
	private int totalRow;

	/**
	 * 每页记录数
	 */
	private int pageSize = 10;

	/**
	 * 当前页码
	 */
	private int currentCount;

	/**
	 * 总页数
	 */
	private int total;

	/**
	 * 起始记录下标
	 */
	private int beginIndex;

	/**
	 * 截止记录下标
	 */
	private int endIndex;

	/**
	 * 构造方法,使用总记录数,当前页码
	 * 
	 * @param totalRow
	 *            总记录数
	 * @param currentCount
	 *            当前页面,从1开始
	 */
	public Page(int totalRow, int currentCount) {
		this.totalRow = totalRow;
		this.currentCount = currentCount;
		calculate();
	}

	/**
	 * 构造方法 ,利用总记录数,当前页面
	 * 
	 * @param totalRow
	 *            总记录数
	 * @param currentCount
	 *            当前页面
	 * @param pageSize
	 *            默认10条
	 */
	public Page(int totalRow, int currentCount, int pageSize) {
		this.totalRow = totalRow;
		this.currentCount = currentCount;
		this.pageSize = pageSize;
		calculate();
	}

	private void calculate() {
		total = totalRow / pageSize + ((totalRow % pageSize) > 0 ? 1 : 0);

		if (currentCount > total) {
			currentCount = total;
		} else if (currentCount < 1) {
			currentCount = 1;
		}

		beginIndex = (currentCount - 1) * pageSize;
		endIndex = beginIndex + pageSize;
		if (endIndex > totalRow) {
			endIndex = totalRow;
		}
	}

	public int getTotalRow() {
		return totalRow;
	}

	public int getPageSize() {
		return pageSize;
	}

	public int getCurrentCount() {
		return currentCount;
	}

	public int getTotal() {
		return total;
	}

	public int getBeginIndex() {
		return beginIndex;
	}

	public int getEndIndex() {
		return endIndex;
	}

}

 继续

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

Java代码 复制代码 收藏代码
  1. int currentPage = 1;     
  2. try {     
  3.     currentPage = Integer.parseInt(request.getParameter("currentPage"));     
  4. catch (Exception ex) {}     
  5.      
  6. //取得总记录数,创建Page对象     
  7. int totalRow = studentDao.getAllStudents();//通过select count 取得总记录数     
  8. Page page = new Page(totalRow, currentPage);     
  9. studentDao.list(page);    
    int currentPage = 1;  
    try {  
    	currentPage = Integer.parseInt(request.getParameter("currentPage"));  
    } catch (Exception ex) {}  
      
    //取得总记录数,创建Page对象  
    int totalRow = studentDao.getAllStudents();//通过select count 取得总记录数  
    Page page = new Page(totalRow, currentPage);  
    studentDao.list(page);  

 

数据访问层,StduentDao.java

Java代码 复制代码 收藏代码
  1. public List<Stduent> getStudentsByPage(Page page) {     
  2.         List<Stduent> students = new ArrayList<Stduent>();     
  3.         try {     
  4.             String sql = "SELECT id,name,email FROM tbl_stduent";     
  5.             Connection conn = null;     
  6.             try {     
  7.                 conn = DbUtil.getConnection();     
  8.                 Statement statement = conn.createStatement();     
  9.                 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.     }    
public List<Stduent> getStudentsByPage(Page page) {  
        List<Stduent> students = new ArrayList<Stduent>();  
        try {  
            String sql = "SELECT id,name,email FROM tbl_stduent";  
            Connection conn = null;  
            try {  
                conn = DbUtil.getConnection();  
                Statement statement = conn.createStatement();  
                statement.setMaxRows(page.getEndIndex());//关键代码,设置最大记录数为当前页记录的截止下标  
                ResultSet resultSet = statement.executeQuery(sql);  
                if (page.getBeginIndex() > 0) {  
                	resultSet.absolute(page.getBeginIndex());//关键代码,直接移动游标为当前页起始记录处  
                }  
                while (resultSet.next()) {  
                    Stduent student = new Student();  
                    ……  
                    students.add(student);  
                }  
                resultSet.close();  
                statement.close();  
            } finally {  
                if (conn != null) {  
                    conn.close();  
                }  
            }  
        } catch (SQLException e) {  
            e.printStackTrace();  
        }  
        return students;  
    }  

 其实仔细想想JDBC分页的性能与页码有关即与statement.setMaxRows有效,越往后翻,性能越差,因为越往后一次性查询的记录数就多,但是我们从用户的角度来看不会有用户会牛逼的一页一页翻到第n页去,一般都是根据条件来缩小查询范围。所以折中的办法就是将记录数设大一点,另外就是限制用户翻页的范围,其实这些性能的前提都是在数据量非常大的情况下而言的,一般数据量少的话,基本上都可以忽略不计的。

分享到:
评论

相关推荐

    Java jdbc分页工具类

    java jdbc 分页工具类,以及返回集合数据的封装, private int limit = 10;//每页的个数 /** * 当前页 */ private int page; // /** * 总行数 */ private int totalRows; // /** * 总页数 */ private ...

    原创强大的jdbc数据库操作工具类

    原创强大的jdbc数据库操作工具类: 1.获取数据源 2.设置数据源 3.获取数据库连接 4.执行insert/delete语句,一个参数列表 public static boolean excute(String sql, List args) 5.执行insert/delete语句,多个参数...

    jdbc经典工具类

    我自己写的,jdbc工具类。驱动、连接地址、用户名等信息可以通过一个properties配置文件进行配置,非常方便。嘿嘿。

    jdbc工具类

    基于jdbc的封装,轻量级映射,自带连接池,无第三方依赖。支持多数据源,配置简单,支持注解sql查询,自带分页查询。

    JDBC数据库操作工具类

    简单封装JDBC操作数据库,实现了增删改查和分页的操作,直接调用工具类方法即可,其中用到了Apache的beanUtils工具类。

    SpringJdbcTemplate封装工具类

    SpringJdbcTemplate封装工具包,包括规范model格式接口,封装SpringJdbcTemplate,实现分页,自适应多种数据库

    MySql + JDBC +EasyUI DataGrid实现数据表格的展示和分页

    使用JDBC实现数据库工具类,使用工具类连接数据库,使用EasyUI连接后台实现数据表格的展示和分页功能

    邮件发送 poi 二维码 条形码等java常用的工具类

    PageUtil:分页工具类, POIUtil:poi工具类,excel导出 QrCodeUtil:二维码操作工具, 包括生成和读取 ShellUtil:shell命令操作工具,包括linux登陆,命令执行...... 较为简单,具体需要自行扩充 SignUtil:...

    关于Hibernate分页类和jdbc的sql分页完美融合

    NULL 博文链接:https://jeffenchung.iteye.com/blog/1472402

    java各种常用的工具类封装 源码

    dateUtil fileUtil propertyUtil 反射 json 分页 jdbc struts2 string 一些java开发 常用的工具类的总结 封装

    jdbc封装(实现对实体的增删改查[分页]).zip

    JdbcUtils是jdbc封装的工具, JdbcCRUDUtils借助JdbcUtils实现对实体的增删改查(分页).尤其是分页,最终结果可实现只需给方法传两个参数即可取得分页数据.那两个参数分别是[显示页数]\[每页显示数] ----------...

    jsp+servlet+oracle模仿百度分页

    比较适合初学者参考,jdbc工具类是自己写的,没有使用第三方分页组件。tomcat是apache-tomcat-7.0.41,myeclipse是MyEclipse 9.0,oracle是11g。例子中用的是海量数据账户sh下的sales表,如果想运行的话,需要对sh...

    基于SpringMVC的一个web框架

    socket工具类,权限组件,菜单组件,jdbc分页支持多种数据库,ant路径工具类,增加jquery easyUI 1.0.9 版本管理,服务根路径工具类,文件上传工具类 1.0.10 集成ueditor在线编辑器 1.0.11 地址联动 1.0.12 Excel工具类 ...

    JDBC 3.0数据库开发与设计

    1.4 JDBC 3.0中的类和接口 1.4.1 java.sql包中的类和接口及其使用 1.4.2 javax.sql包中所含内容及其使用 1.5 JDBC驱动程序简介 1.5.1 JDBC-ODBC 桥和ODBC驱动程序 1.5.2 本地API部分Java驱动程序 1.5.3 JDBC...

    基于Spring MVC的web框架 1.1.11

    socket工具类,权限组件,菜单组件,jdbc分页支持多种数据库,ant路径工具类,增加jquery easyUI 1.0.9 版本管理,服务根路径工具类,文件上传工具类 1.0.10 集成ueditor在线编辑器 1.0.11 地址联动 1.0.12 Excel工具类 ...

    一个可以直接运行的基于SpringMVC的web框架1.1.12

    socket工具类,权限组件,菜单组件,jdbc分页支持多种数据库,ant路径工具类,增加jquery easyUI 1.0.9 版本管理,服务根路径工具类,文件上传工具类 1.0.10 集成ueditor在线编辑器 1.0.11 地址联动 1.0.12 Excel工具类 ...

    JDBC DAO代碼自码动生成工具

    此小工具能更据mysql数据库中的表结构,自动生成JDBC DAO类和接口,包括单表操作的CRUD方法,其中包含分页方法。此工具用swing做的界面,使用简单方便。需要源码,请发邮件至763863446@qq.com。

    可以直接运行的基于SpringMVC的web框架示例,也可以直接当公司框架

    socket工具类,权限组件,菜单组件,jdbc分页支持多种数据库,ant路径工具类,增加jquery easyUI 1.0.9 版本管理,服务根路径工具类,文件上传工具类 1.0.10 集成ueditor在线编辑器 1.0.11 地址联动 1.0.12 Excel工具类 ...

    SpringMVC基础上的web框架

    socket工具类,权限组件,菜单组件,jdbc分页支持多种数据库,ant路径工具类,增加jquery easyUI 1.0.9 版本管理,服务根路径工具类,文件上传工具类 1.0.10 集成ueditor在线编辑器 1.0.11 地址联动 1.0.12 Excel工具类 ...

    自己收集的JAVA工具类

    自己收集的JAVA工具类,有“配置文件读取”,“验证码生成”,“分页器”,“JSP导出excel”,“MD5加密”,“JDBC工具”,“数据源”,“listener”等

Global site tag (gtag.js) - Google Analytics