由于是用mvc这样的框架,所以在c这一层仅仅起到一个转向和收集页面信息的作用,所以这里我有写了一个分页查询的bean,暂时命名是PageCtBean,代码如下:
package com.util;
import com.model.DBUtil; import java.sql.*; /** * Created by IntelliJ IDEA. * User: 7612ce * Date: 2005-6-23 * Time: 10:36:57 * To change this template use Options | File Templates. */ public class PageCtBean { public final static int MAX_PAGE_SIZE = Page.MAX_PAGE_SIZE; protected String countSQL, querySQL; protected int pageNo,pageSize,startIndex,totalCount; protected javax.sql.RowSet rowSet; protected Page setPage; protected Object[][] objTables=null; protected Object[][] objCount=null; protected Object[] obj=null;
public PageCtBean(){
} /** * 构造一查询出所有数据的PageStatement * @param sql query sql */ public PageCtBean(String sql){ this(sql,1,MAX_PAGE_SIZE); } /** * 构造一查询出当页数据的PageStatement * @param sql query sql * @param pageNo 页码 */ public PageCtBean(String sql, int pageNo){ this(sql, pageNo, Page.DEFAULT_PAGE_SIZE); }
/** * 构造一查询出当页数据的PageStatement,并指定每页显示记录条数 * @param sql query sql * @param pageNo 页码 * @param pageSize 每页容量 */ public PageCtBean(String sql, int pageNo, int pageSize){ this.pageNo = pageNo; this.pageSize = pageSize; this.startIndex = Page.getStartOfAnyPage(pageNo, pageSize); this.querySQL = intiQuerySQL(sql, this.startIndex, pageSize); }
/** *生成查询一页数据的sql语句 *@param sql 原查询语句 *@ startIndex 开始记录位置 *@ size 需要获取的记录数 */ protected String intiQuerySQL(String sql, int startIndex, int size){ StringBuffer querySQL = new StringBuffer(); querySQL.append(sql) .append(" limit ") .append(startIndex-1 ) .append(",").append(size); return querySQL.toString(); }
/** *使用给出的对象设置指定参数的值 *@param obj 包含参数值的对象 */ public void setObject(Object obj[]) throws SQLException{ this.obj=obj; }
public void setCountSql(String sql){ this.countSQL=sql; } /** * 执行查询取得一页数据,执行结束后关闭数据库连接 * @return RowSetPage * @throws SQLException */ public Page executeQuery() throws ClassNotFoundException{ System.out.println("executeQueryUsingPreparedStatement"); DBUtil DBean=new DBUtil(); try{ objCount = DBean.doSearch(this.countSQL,obj); if (!objCount.equals(null)){ System.out.println("the count is ="+objCount[0][0].toString()); totalCount =Integer.parseInt(objCount[0][0].toString()) ; System.out.println("the count is ="+totalCount); } else { totalCount = 0; } if (totalCount < 1 ) return null; objTables= DBean.doSearch(this.querySQL,obj); this.setPage = new Page(this.objTables,startIndex,totalCount,pageSize); return this.setPage; }catch(SQLException sqle){ //System.out.println("executeQuery SQLException"); sqle.printStackTrace();
}catch(Exception e){ e.printStackTrace(); throw new RuntimeException(e.toString()); } return null; } /** *取封装成Page的查询结果 *@return Page */ public Page getPage() { return this.setPage; } }
|