Java_web分頁程式碼
阿新 • • 發佈:2018-11-22
package com.fengjing.webphonebook.db; import Java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; public class DB { public static Connection getConnection() throws Exception{ Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); Connection conn = DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;databasename=address","sa",""); return conn; } public static PreparedStatement getPstmt(Connection conn, String sql) throws Exception{ PreparedStatement pstmt = conn.prepareStatement(sql); return pstmt; } public static Statement getStmt(Connection conn) throws Exception{ Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); return stmt; } public static ResultSet getRs(Statement stmt,String sql) throws Exception{ ResultSet rs = stmt.executeQuery(sql); return rs; } public static void close(Connection conn, Statement stmt, ResultSet rs) throws Exception{ if(rs != null){ rs.close(); } if(stmt != null){ stmt.close(); } if(conn != null){ conn.close(); } } public static void close(Connection conn, Statement stmt) throws Exception{ if(stmt != null){ stmt.close(); } if(conn != null){ conn.close(); } } } PageBean類程式碼: package com.fengjing.webphonebook.util; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import com.fengjing.webphonebook.db.DB; import com.fengjing.webphonebook.vo.Address; public class PageBean { //每頁顯示多少行 private int pageSize = 4; //總共多少頁 private int pageNum; //當前是第幾頁 private int pageId; //資料庫中總共多少條記錄 private int size; @SuppressWarnings("unchecked") public List queryAll(int pageId) throws Exception { this.pageId = pageId; Connection conn = null; Statement stmt = null; ResultSet rs = null; if(this.pageId<1) { this.pageId=1; } conn = DB.getConnection(); stmt = DB.getStmt(conn); String sql = "select * from address"; rs = DB.getRs(stmt, sql); //使遊標指向最後一條記錄 rs.last(); //獲取當前結果集合中所有資料的行數 this.size = rs.getRow(); this.pageNum = (size%pageSize==0? size/pageSize:size/pageSize+1); if(this.pageId>this.pageNum) { this.pageId = this.pageNum; } //將遊標重新移動到第一條記錄的前面 rs.beforeFirst(); //步長 for (int i = 0; i < (this.pageId-1)*pageSize; i++) { rs.next(); } List list = new ArrayList(); //控制每頁顯示的條數 for(int j=0;j //判斷是否有下一條記錄 if(!rs.next()) { break; } Address address = new Address(); address.setId(rs.getInt(1)); address.setUid(rs.getInt(2)); address.setPname(rs.getString(3)); address.setPhone(rs.getString(4)); address.setAge(rs.getInt(5)); address.setEmail(rs.getString(6)); address.setAddress(rs.getString(7)); list.add(address); } return list; } public int getPageNum() { return pageNum; } public void setPageNum(int pageNum) { this.pageNum = pageNum; } public int getPageId() { return pageId; } public int getSize() { return size; } }