PageUtils是基于Druid SQL Parser实现的分页SQL自动生成类。目前支持MySql、Oracle、DB2、SQL Server四种数据库类型。

API

  1. package com.alibaba.druid.sql;
  2.  
  3. public class PagerUtils {
  4. // 生成获取count的sql
  5. public static String count(String sql, String dbType) { }
  6. // 生成分页取数的sql
  7. public static String limit(String sql, String dbType, int offset, int count) { }
  8. }

count方法使用介绍

  1. import com.alibaba.druid.sql.PagerUtils;
  2. import com.alibaba.druid.util.JdbcConstants;
  3.  
  4. String sql = "select id, name from t order by id";
  5. String result = PagerUtils.count(sql, JdbcConstants.MYSQL); // 这里的dbType是MySql,可以更换为Oracle、DB2和SQL_Server

输出结果

  1. SELECT COUNT(*)
  2. FROM t

count方法能够自动去掉selectList上字段,也能够去掉order by,能够自动识别union

limit使用介绍

  1. String sql = "select * from t";
  2. String result = PagerUtils.limit(sql, JdbcConstants.ORACLE, 20, 10);

输出结果

  1. SELECT *
  2. FROM (SELECT XX.*, ROWNUM AS RN
  3. FROM (SELECT *
  4. FROM t
  5. ) XX
  6. WHERE ROWNUM <= 30
  7. ) XXX
  8. WHERE RN > 20

hasUnorderedLimit

  1. String sql = " select * from test t limit 3";
  2. assertTrue(PagerUtils.hasUnorderedLimit(sql, JdbcConstants.MYSQL));