2007-04-12 15:55
一、建立数据库分页的类 package newsbean; import java.sql.*;
public class DBConnection{ //这里使用 ms jdbc String sDBDriver = "com.microsoft.jdbc.sqlserver.SQLServerDriver"; //指定数据库名/url private final String url = "jdbc:microsoft:sqlserver://"; private final String serverName= "localsqlserver"; private final String portNumber = "1433"; private final String databaseName= "MyBusiDB"; //String sConnStr = "jdbc:microsoft:sqlserver://localsqlserver:1433;DatabaseN private final String dbUserName = "sa"; private final String dbPassword = "111111"; // Informs the driver to use server a side-cursor, // which permits more than one active statement // on a connection. private final String selectMethod = "cursor"; Connection conn = null; ResultSet rs = null; Statement stmt = null; //这三个参数用于记录翻页 int iRowCount = 0; //返回总行数 int iPageCount = 0; //返回总页数 int iPage = 0; public DBConnection(){ try { Class.forName(sDBDriver); } catch(ClassNotFoundException e) { System.err.println("DBConnection():" + e.getMessage()); } } //构造一个连接字符串
private String getConnectionUrl(){ return url+serverName+":"+portNumber+";databaseName="+databaseName+";selectMethod="+selectMe } //================考虑在类中的分页====================================== //================考虑在类中的分页====================================== 考虑在类中的分页============ //内部设置总条数.. private void setRowCount setRowCount(int irowcount) { this.iRowCount = irowcount; } //返回内部设置的总条数 public int getRowCount() getRowCount { return this.iRowCount; } //内部设置总页数.. private void setPageCount setPageCount(int ipagecount) { this.iPageCount = ipagecount; } //返回内部设置的总页数 public int getPageCount getPageCount() { return this.iPageCount; } //内部设置当前页.. private void setPage setPage(int ipage) { this.iPage = ipage; } //返回内部设置的总页数 public int getPage getPage() { return this.iPage; }
//显示翻页信息 //参数:总页数,总行数,当前页 //应该考虑加一个查询参数列表进入本方法--2007-4-12 public String showChangePage() { return this.iPage + "/" + this.iPageCount + ">>>";
}
//考虑了翻页的选择查询 sql,int iPage) public ResultSet execQuery(String sql,int iPageSize,int iPage) {//======iRowCount== iPageCount==iPageSize===iPage================ try { conn = DriverManager.getConnection(getConnectionUrl(),dbUserName,dbPass stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPD rs = stmt.executeQuery(sql); rs.last(); //获取总行数 移动到最后,检索当前行编号。 int iRowCount rs.getRow(); iRowCount= //计算总页数 总 100 行 每页 10 行===〉总页数= 11.4 页==> 12 页 int iPageCount = (iRowCount + iPageSize iPageSize-1) / iPageSize; if(iPage iPage>iPageCount) iPage = iPageCount; iPage if(iPage <= 0 ) iPage = 1; if(iPageCount>0){
//在方法体中已经到了指定行 rs.absolute((iPage-1) * iPageSize +1); } //自己设置 iPageCount 和 iRowCount,iPage,避免混淆?! //自己设置 iRowCount,iPage, 避免混淆?! setPageCount(iPageCount); setRowCount(iRowCount); setPage(iPage); //stmt.close();??? }//end try catch(SQLException ex) { System.err.println("DBConnection.execQuery():" + ex.getMessage()); }//end catch return rs; }//end execQuery //================