JDBC高效分页

一个继承ArrayList类的ResultSet,一个继承HashMap的Record

执行,把java.sql.ResultSet对象中的一列封装成Record,加到ArrayList类型的ResultSet对象中
 /**
     * 执行 SQL 语句 (带分页功能)
     * @param con 数据库链接 Connection
     * @param strSQL SQL语句
     * @param nCommonPageSize 每页最大记录数
     * @param nCurrentPage 当前页号
     * @param nTotalRecordCount 总记录数, 如果等于 -1 或小于 0, 则由本函数相关方法得到此值
     * @param obj 字段对象
     * @return 如果执行的是查询操作(select ...), 成功返回封装成 RecordSet 的记录集, 异常或失败返回 null
     *  如果执行的是写操作, 成功返回空的 RecordSet(含操作的记录个数), 异常或失败返回 null
     */
    public static RecordSet executeWithDefaultDriver(Connection con, String strSQL, int nCommonPageSize, int nCurrentPage, int nTotalRecordCount, Object[] obj)
    {
      PreparedStatement ps = null;
      try
      {
        if(nCommonPageSize<=0)
          throw new Exception("页记录数小于 0: (" + nCommonPageSize + " 条记录/页)");
        if(nCurrentPage<=0)
          throw new Exception("页数小于 0: (第 " + nCurrentPage + " 页)");
        RecordSet set = new RecordSet();
        strSQL = strSQL.trim();
        ps = con.prepareStatement(strSQL, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        //设置字段值
        setFieldValue(ps, obj, strSQL);
        //判断是否为查询 SQL, 还是更新 SQL
        if(strSQL.substring(0, strSQL.indexOf(" ")).equalsIgnoreCase("SELECT"))
        {
          ResultSet rs = ps.executeQuery();
          ResultSetMetaData rsmd = rs.getMetaData();
          int nColumn = rsmd.getColumnCount();
          //移到结果集最后一条, 取得记录总数
          set.CURRENT_PAGE = nCurrentPage;
          set.COMMON_PAGE_SIZE = nCommonPageSize;
          if(nTotalRecordCount>=0)
            set.TOTAL_RECORD_COUNT = nTotalRecordCount;
          else
          {
            rs.last();
            set.TOTAL_RECORD_COUNT = rs.getRow();
          }
          set.TOTAL_PAGE = (set.TOTAL_RECORD_COUNT + nCommonPageSize - 1) / nCommonPageSize;
          if(nCurrentPage==set.TOTAL_PAGE && set.TOTAL_RECORD_COUNT%nCommonPageSize!=0)
            set.CURRENT_PAGE_SIZE = set.TOTAL_RECORD_COUNT % nCommonPageSize;
          else
            set.CURRENT_PAGE_SIZE = nCommonPageSize;
          if(set.TOTAL_RECORD_COUNT==0)
            return set;
          //定位到当前页的页首
          rs.absolute(nCommonPageSize * (nCurrentPage - 1) + 1);
          do
          {
            Record record = new Record();
            for(int i=0;i<nColumn;i++)
            {
              String strField = rsmd.getColumnName(i+1).toUpperCase();
              record.put(strField, rs.getObject(i+1));
            }
            set.add(record);
          }
          while(rs.getRow()<nCommonPageSize*nCurrentPage && rs.next());
          rs.close();
        }
        else
          set.TOTAL_RECORD_COUNT = ps.executeUpdate();
        return set;
      }
      catch(Exception e)
      {
        e.printStackTrace();
        return null;
      }
      finally
      {
        try
        {
          if(ps!=null)
            ps.close();
        }
        catch(Exception e){}
      }
    }

静态方法直接调用,返回RS

调用
 Record record =(Record)rs.get(i);
 String code=record.getString("code");

取翻页信息
<td valign="middle" align="right">每页<%=rs.COMMON_PAGE_SIZE%>行
 共<%=rs.TOTAL_RECORD_COUNT%>行
 第<%=rs.CURRENT_PAGE%>页
 共<%=rs.TOTAL_PAGE%>页
 <BR>
 <%if(rs.CURRENT_PAGE==1){ out.print(" 首页 上一页");   }else{  %>
 <A HREF="javascript:gotoPage(1)">首页</A>
 <A HREF="javascript:gotoPage(<%=rs.CURRENT_PAGE-1%>)">上一页</A>
 <%}%>
 <%if(rs.CURRENT_PAGE==rs.TOTAL_PAGE){ out.print("下一页 尾页");   }else{  %>
 <A HREF="javascript:gotoPage(<%=rs.CURRENT_PAGE+1%>)">下一页</A>
 <A HREF="javascript:gotoPage(<%=rs.TOTAL_PAGE%>)">尾页</A>
 <%}%>
 转到第<SELECT name="jumpPage" οnchange="Jumping()">
    <% for(int i=1;i<=rs.TOTAL_PAGE;i++)  {
    if (i== rs.CURRENT_PAGE){
    %>
    <OPTION selected value=<%=i%>><%=i%></OPTION>
    <%}else{%>
    <OPTION value=<%=i%>><%=i%></OPTION>
    <%}}%>
    </SELECT>页
</td>


//RecordSet.java///
import java.util.*;

public class RecordSet
    extends ArrayList {

  // 记录集信息
  /** 总页数 */
  public int TOTAL_PAGE = -1;
  /** 当前页号 */
  public int CURRENT_PAGE = -1;
  /** 每页最大记录数 */
  public int COMMON_PAGE_SIZE = -1;
  /** 当前页所含记录数 */
  public int CURRENT_PAGE_SIZE = -1;
  /** 总记录数 */
  public int TOTAL_RECORD_COUNT = -1;

  /** 当前指向的记录位置 ( 初始位置在第一条记录之前的空位上 ) */
  private int currentRecordRow = 0;

  /**
   * 取得当前记录的位置
   * @return 记录的位置
   */
  public int getRow() {
    return currentRecordRow;
  }

  /**
   * 得到第n条记录
   * @param i 记录位置 ( 取值范围: 1--返回的记录数 )
   * @return 成功返回记录, 异常或失败返回 false
   */
  public Record getRecord(int i) {
    try {
      return (Record)this.get(i - 1);
    }
    catch (Exception e) {
      //Log.error(e);
      return null;
    }
  }

  /**
   * 得到当前记录
   * @return 成功返回记录, 异常或失败返回 false
   */
  public Record getRecord() {
    if (isBeforeFirst()) {
      //Log.warn("指针在初始位置, 请使用 first() 或 next() 方法将指针指向第一条记录");
      return null;
    }
    if (isAfterLast()) {
      //Log.warn("指针在结束位置, 请使用 first() 方法将指针指向第一条记录");
      return null;
    }
    return getRecord(currentRecordRow);
  }

  /**
   * 定位到绝对位置的记录
   * @param row 记录位置 ( 0--返回的记录数+1 )
   * @return 成功返回 true, 异常或失败返回 false
   */
  public boolean absolute(int row) {
    if (0 <= row && row <= this.size() + 1) {
      currentRecordRow = row;
      return true;
    }
    else {
      return false;
    }
  }

  /**
   * 定位到首条记录之前
   */
  public void beforeFirst() {
    currentRecordRow = 0;
  }

  /**
   * 定位到末条记录之后
   */
  public void afterLast() {
    currentRecordRow = this.size() + 1;
  }

  /**
   * 定位到首条记录
   * @return 成功返回 true, 失败返回 false
   */
  public boolean first() {
    if (this.isEmpty()) {
      return false;
    }
    else {
      currentRecordRow = 1;
      return true;
    }
  }

  /**
   * 定位到末条记录
   * @return 成功返回 true, 失败返回 false
   */
  public boolean last() {
    if (this.isEmpty()) {
      return false;
    }
    else {
      currentRecordRow = this.size();
      return true;
    }
  }

  /**
   * 是否在首条记录之前
   * @return 是返回 true, 否返回 false
   */
  public boolean isBeforeFirst() {
    if (currentRecordRow == 0) {
      return true;
    }
    else {
      return false;
    }
  }

  /**
   * 是否在末条记录之后
   * @return 是返回 true, 否返回 false
   */
  public boolean isAfterLast() {
    if (currentRecordRow == this.size() + 1) {
      return true;
    }
    else {
      return false;
    }
  }

  /**
   * 是否位于首条记录
   * @return 是返回 true, 否返回 false
   */
  public boolean isFirst() {
    if (this.isEmpty()) {
      return false;
    }
    else {
      if (currentRecordRow == 1) {
        return true;
      }
      else {
        return false;
      }
    }
  }

  /**
   * 是否位于末条记录
   * @return 是返回 true, 否返回 false
   */
  public boolean isLast() {
    if (this.isEmpty()) {
      return false;
    }
    else {
      if (currentRecordRow == this.size()) {
        return true;
      }
      else {
        return false;
      }
    }
  }

  /**
   * 定位到前一条记录
   * @return 成功返回 true, 失败返回 false
   */
  public boolean previous() {
    if (currentRecordRow < 1) {
      return false;
    }
    else {
      currentRecordRow--;
      if (currentRecordRow < 1) {
        return false;
      }
      else {
        return true;
      }
    }
  }

  /**
   * 定位到后一条记录
   * @return 成功返回 true, 失败返回 false
   */
  public boolean next() {
    if (currentRecordRow > this.size()) {
      return false;
    }
    else {
      currentRecordRow++;
      if (currentRecordRow > this.size()) {
        return false;
      }
      else {
        return true;
      }
    }
  }

  /**
   * 得到数字(推荐使用这个方法得到数字, 可以避免各种数据库数据类型不同而产生的问题)
   * @param key 字段名
   * @return 数字
   */
  public double getNumber(String key) {
    return Double.parseDouble(getString(key));
  }

  /**
   * 得到 String 类型的值(用 getObject 方法取得, 并使用了 trim 方法去掉两端空格, 当对象为空时返回空字符串)
   * @param key 字段名
   * @return String 类型的值
   */
  public String getString(String key) {
    Object obj = this.getRecord().getObject(key);
    if (obj == null) {
      return "";
    }
    else {
      return obj.toString().trim();
    }
  }

  /**
   * 得到 Timestamp 类型的值
   * @param key 字段名
   * @return Timestamp 类型的值
   */
  public java.sql.Timestamp getTimestamp(String key) {
    return this.getRecord().getTimestamp(key);
  }

  /**
   * 得到 Date 类型的值
   * @param key 字段名
   * @return Date 类型的值
   */
  public java.sql.Date getDate(String key) {
    return this.getRecord().getDate(key);
  }

  /**
   * 得到 Time 类型的值
   * @param key 字段名
   * @return Time 类型的值
   */
  public java.sql.Time getTime(String key) {
    return this.getRecord().getTime(key);
  }

  /**
   * 得到 BigDecimal 类型的值
   * @param key 字段名
   * @return BigDecimal 类型的值
   */
  public java.math.BigDecimal getBigDecimal(String key) {
    return this.getRecord().getBigDecimal(key);
  }

  /**
   * 得到 long 类型的值
   * @param key 字段名
   * @return long 类型的值
   */
  public long getLong(String key) {
    return this.getRecord().getLong(key).longValue();
  }

  /**
   * 得到 int 类型的值
   * @param key 字段名
   * @return int 类型的值
   */
  public int getInt(String key) {
    return this.getRecord().getInteger(key).intValue();
  }

  /**
   * 得到 short 类型的值
   * @param key 字段名
   * @return short 类型的值
   */
  public short getShort(String key) {
    return this.getRecord().getShort(key).shortValue();
  }

  /**
   * 得到 double 类型的值
   * @param key 字段名
   * @return double 类型的值
   */
  public double getDouble(String key) {
    return this.getRecord().getDouble(key).doubleValue();
  }

  /**
   * 得到 float 类型的值
   * @param key 字段名
   * @return float 类型的值
   */
  public float getFloat(String key) {
    return this.getRecord().getFloat(key).floatValue();
  }

  /**
   * 得到 boolean 类型的值
   * @param key 字段名
   * @return boolean 类型的值
   */
  public boolean getBoolean(String key) {
    return this.getRecord().getBoolean(key).booleanValue();
  }

  /**
   * 得到 byte 类型的值
   * @param key 字段名
   * @return byte 类型的值
   */
  public byte getByte(String key) {
    return this.getRecord().getByte(key).byteValue();
  }

  /**
   * 得到 byte[] 类型的值
   * @param key 字段名
   * @return byte[] 类型的值
   */
  public byte[] getBytes(String key) {
    return this.getRecord().getBytes(key);
  }

  /**
   * 得到 Blob 类型的值
   * @param key 字段名
   * @return Blob 类型的值
   */
  public java.sql.Blob getBlob(String key) {
    return this.getRecord().getBlob(key);
  }

  /**
   * 得到 Clob 类型的值
   * @param key 字段名
   * @return Clob 类型的值
   */
  public java.sql.Clob getClob(String key) {
    return this.getRecord().getClob(key);
  }

  /**
   * 得到 Array 类型的值
   * @param key 字段名
   * @return Array 类型的值
   */
  public java.sql.Array getArray(String key) {
    return this.getRecord().getArray(key);
  }

  /**
   * 得到 InputStream 类型的值
   * @param key 字段名
   * @return InputStream 类型的值
   */
  public java.io.InputStream getBinaryStream(String key) {
    return this.getRecord().getBinaryStream(key);
  }

  /**
   * 得到 Object 类型的值
   * 注意: 如果字段为 char 类型, 要注意返回的值尾部是否有多余的空格
   * @param key 字段名
   * @return Object 类型的值
   */
  public Object getObject(String key) {
    return this.getRecord().getObject(key);
  }

  /**
   * 返回相邻的页号
   * @param size 相邻的页数
   * @return 成功返回所有相邻的页号集合, 失败返回 null
   */
  public int[] getNeighbouringPage(int size) {
    try {
      int left = (this.CURRENT_PAGE - 1 > size) ? size : this.CURRENT_PAGE - 1;
          int right = (this.TOTAL_PAGE - this.CURRENT_PAGE > size) ? size :
          this.TOTAL_PAGE - this.CURRENT_PAGE;
          int begin = this.CURRENT_PAGE - left;
      int[] num = new int[left + 1 + right];
      for (int i = 0; i < num.length; i++) {
        num[i] = begin + i;
      }
      return num;
    }
    catch (Exception e) {
      //Log.error(e);
      return null;
    }
  }

  /**
   * 与另一个记录集合并
   * @param rs 记录集
   */
  public void merge(RecordSet rs) {
    try {
      rs.beforeFirst();
      while (rs.next()) {
        this.add(rs.getRecord());
      }
      this.TOTAL_RECORD_COUNT += rs.TOTAL_RECORD_COUNT;
      this.beforeFirst();
    }
    catch (Exception e) {
      //Log.error(e);
    }
  }
}

//Record.java///

import java.util.*;

public class Record
    extends HashMap {

  /**
   * 取得字段的值
   * @param key 字段名
   * @return 成功返回字段的取值, 异常或失败返回 null
   */
  public Object get(String key) {
    if (key == null) {
      return null;
    }
    else {
      return super.get(key.toUpperCase());
    }
  }

  /**
   * 得到 String 类型的值
   * @param key 字段名
   * @return String 类型的值
   */
  public java.lang.String getString(String key) {
    Object obj = this.get(key);
    return (java.lang.String) obj;
  }

  /**
   * 得到 Timestamp 类型的值
   * @param key 字段名
   * @return Timestamp 类型的值
   */
  public java.sql.Timestamp getTimestamp(String key) {
    Object obj = this.get(key);
    return (java.sql.Timestamp) obj;
  }

  /**
   * 得到 Date 类型的值
   * @param key 字段名
   * @return Date 类型的值
   */
  public java.sql.Date getDate(String key) {
    Object obj = this.get(key);
    return (java.sql.Date) obj;
  }

  /**
   * 得到 Time 类型的值
   * @param key 字段名
   * @return Time 类型的值
   */
  public java.sql.Time getTime(String key) {
    Object obj = this.get(key);
    return (java.sql.Time) obj;
  }

  /**
   * 得到 BigDecimal 类型的值
   * @param key 字段名
   * @return BigDecimal 类型的值
   */
  public java.math.BigDecimal getBigDecimal(String key) {
    Object obj = this.get(key);
    return (java.math.BigDecimal) obj;
  }

  /**
   * 得到 Long 类型的值
   * @param key 字段名
   * @return Long 类型的值
   */
  public java.lang.Long getLong(String key) {
    Object obj = this.get(key);
    return (java.lang.Long) obj;
  }

  /**
   * 得到 Integer 类型的值
   * @param key 字段名
   * @return Integer 类型的值
   */
  public java.lang.Integer getInteger(String key) {
    Object obj = this.get(key);
    return (java.lang.Integer) obj;
  }

  /**
   * 得到 Short 类型的值
   * @param key 字段名
   * @return Short 类型的值
   */
  public java.lang.Short getShort(String key) {
    Object obj = this.get(key);
    return (java.lang.Short) obj;
  }

  /**
   * 得到 Double 类型的值
   * @param key 字段名
   * @return Double 类型的值
   */
  public java.lang.Double getDouble(String key) {
    Object obj = this.get(key);
    return (java.lang.Double) obj;
  }

  /**
   * 得到 Float 类型的值
   * @param key 字段名
   * @return Float 类型的值
   */
  public java.lang.Float getFloat(String key) {
    Object obj = this.get(key);
    return (java.lang.Float) obj;
  }

  /**
   * 得到 Boolean 类型的值
   * @param key 字段名
   * @return Boolean 类型的值
   */
  public java.lang.Boolean getBoolean(String key) {
    Object obj = this.get(key);
    return (java.lang.Boolean) obj;
  }

  /**
   * 得到 Byte 类型的值
   * @param key 字段名
   * @return Byte 类型的值
   */
  public java.lang.Byte getByte(String key) {
    Object obj = this.get(key);
    return (java.lang.Byte) obj;
  }

  /**
   * 得到 byte[] 类型的值
   * @param key 字段名
   * @return byte[] 类型的值
   */
  public byte[] getBytes(String key) {
    Object obj = this.get(key);
    return (byte[]) obj;
  }

  /**
   * 得到 Blob 类型的值
   * @param key 字段名
   * @return Blob 类型的值
   */
  public java.sql.Blob getBlob(String key) {
    Object obj = this.get(key);
    return (java.sql.Blob) obj;
  }

  /**
   * 得到 Clob 类型的值
   * @param key 字段名
   * @return Clob 类型的值
   */
  public java.sql.Clob getClob(String key) {
    Object obj = this.get(key);
    return (java.sql.Clob) obj;
  }

  /**
   * 得到 Array 类型的值
   * @param key 字段名
   * @return Array 类型的值
   */
  public java.sql.Array getArray(String key) {
    Object obj = this.get(key);
    return (java.sql.Array) obj;
  }

  /**
   * 得到 InputStream 类型的值
   * @param key 字段名
   * @return InputStream 类型的值
   */
  public java.io.InputStream getBinaryStream(String key) {
    Object obj = this.get(key);
    return (java.io.InputStream) obj;
  }

  /**
   * 得到 Object 类型的值
   * @param key 字段名
   * @return Object 类型的值
   */
  public Object getObject(String key) {
    return this.get(key);
  }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值