//Source file: C:\\Rose2Java\\zhsoft\\dbcon\\QueryPage.java

package com.dbms.dbcon;


/**
 * 查询结果分页处理
 *
 * @author 雨亦奇(zhsoft88@sohu.com)
 * @version 1.0
 * @since 2003.05.18
 */
public class QueryPage
{

    /**
     * 每页行数
     */
    private int linesPerPage = 1;

    /**
     * 总页数
     */
    private int totalPages = 1;

    /**
     * 查询结果集
     */
    private QueryResult result = null;

    /**
     * @roseuid 3ED8688102EC
     */
    public QueryPage()
    {

    }

    /**
     * Access method for the linesPerPage property.
     *
     * @return   the current value of the linesPerPage property
     */
    public int getLinesPerPage()
    {
        return linesPerPage;
    }

    /**
     * Access method for the totalPages property.
     *
     * @return   the current value of the totalPages property
     */
    public int getTotalPages()
    {
        return totalPages;
    }

    /**
     * 初始化查询
     *
     * @param sql
     *  - 查询SQL语句
     * @param linesPerPage
     *  - 用户指定的每页行数
     * @throws java.lang.Exception
     * @roseuid 3ED8098600F8
     */
    public void init(String sql, int linesPerPage) throws Exception
    {
        if (linesPerPage<1) {
            throw new Exception("每页行数应大于等于1");
        }
        result = DBCon.runQuery(sql);
        this.linesPerPage = linesPerPage;
        totalPages = result.size()/linesPerPage;
        if (result.size()%linesPerPage!=0) {
            totalPages++;
        }
        if (totalPages==0) {
            totalPages = 1;
        }
    }

    /**
     * 是否已初始化
     *
     * @return boolean
     * @roseuid 3ED8098A0379
     */
    public boolean isInit()
    {
        if (result==null) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 返回指定页的查询结果
     *
     * @param pageno - 指定页号
     * @return ResultRow[]
     * @throws java.lang.Exception
     * @roseuid 3ED809A20388
     */
    public ResultRow[] getPage(int pageno) throws Exception
    {
        if (pageno<1||pageno>getTotalPages()) {
            throw new Exception("页号范围应为[1.."+getTotalPages()+"]");
        }
        ResultRow[] rr = null;
        if (pageno==getTotalPages()) {
            rr = new ResultRow[result.size()-(pageno-1)*linesPerPage];
        } else {
            rr = new ResultRow[linesPerPage];
        }
        for (int i=0;i<rr.length;i++) {
            rr[i] = (ResultRow)result.getRow((pageno-1)*linesPerPage+i).clone();
        }
        return rr;
    }
}
