java web 分页,以及封装的一个SQL执行类,javasql,package org.
分享于 点击 47970 次 点评:221
java web 分页,以及封装的一个SQL执行类,javasql,package org.
package org.jbit.tools;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.util.List;public class Page { private Connection conn ; // 数据库连接对象 private PreparedStatement ps ; // 预编译sql语句的类 private ResultSet rs ; //返回对象 private int pageSize=5; //每页显示条数 private String tableName; /** * 构造方法,需要传进来一个 连接对象和 一个表名, * 因为分页很少需要表联查,这里就不弄别的了,如果需要表连接的, * 你就之直接来传SQL语句吧... * @param conn * @param tableName */ public Page(Connection conn,String tableName){ this.conn = conn; this.tableName = tableName; } /** * 获取总条数 * @param tableName * @return * @throws Exception */ public int getCount()throws Exception{ int x =0; String sql = "select count(*) from "+this.tableName; this.rs = new SqlExec(conn).fiandSql(sql, null); if(this.rs.next()){ x = this.rs.getInt(1); } return x; }/** * 获取总页数 * @param count 总条数 * @param PageSize 每页显示条数 * @return */ public int getTotalPages()throws Exception{ int x = 0; int count = this.getCount(); x = (count%pageSize)==0?(count/pageSize):(count/pageSize+1); return x; }/** * 返回的是一个rs对象,由外部来接受,然后储存到你的实体类之中.. * @param pageIndex 这个需要传进来的参数是 外部访问的第几页... * @return * @throws Exception */ public ResultSet getPageList(int pageIndex)throws Exception{ String sql ="select * from (select rownum as r,t.* from (select * from "+this.tableName+") t where rownum<="+(this.pageSize*pageIndex)+") where r>"+(this.pageSize*(pageIndex-1)); return new SqlExec(this.conn).fiandSql(sql, null); // 这里是我封装好的一个SQL执行语句的类 }}package org.jbit.tools;import java.sql.*;/** * 提供执行语句的封装操作,慎用! */public class SqlExec { private Connection conn; public SqlExec(Connection conn) { this.conn = conn; } /** * SQL查询语句, * * @param sql * @return 返回Rs对象 */ public ResultSet fiandSql(String sql,String[] str) throws Exception { PreparedStatement ps = this.conn.prepareStatement(sql); if(str!=null&&sql!=null&&!("".equals(sql))){ //如果不为空,就进行插入 for(int x =0 ; x<str.length;x++){ ps.setString((x+1), str[x]); } } return ps.executeQuery(); } /** * SQL更新语句, * * @param sql * @return 返回更新条数 * @throws Exception */ public int doSql(String sql,String[] str) throws Exception { PreparedStatement ps = this.conn.prepareStatement(sql); if(str!=null&&sql!=null&&!("".equals(sql))){ //如果不为空,就进行插入 for(int x =0 ; x<str.length;x++){ ps.setString((x+1),str[x]); } } return ps.executeUpdate(); }}//该片段来自于http://byrx.net
用户点评