package com.basicSql.scroll_page; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.sql.rowset.CachedRowSet; import javax.sql.rowset.RowSetFactory; import javax.sql.rowset.RowSetProvider; import com.basicSql.connUtil.Conndb; /** * 离线RowSet分页查询 * * @author xrhou * */ public class TestCachedRowSet { private static Connection conn = null; private static Statement stmt = null; private static ResultSet rs = null; private static RowSetFactory factory=null; private static CachedRowSet cachedRs=null; public CachedRowSet getRowset(String sql,int pageSize,int page) { try { conn = Conndb.connOracle(); //设置为可滚动后才能成功显示 stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY); rs = stmt.executeQuery(sql); //使用RowSetProvider创建RowSetFactory factory=RowSetProvider.newFactory(); //创建默认的CachedRowSet实例 cachedRs=factory.createCachedRowSet(); //设置每页显示pageSize条记录 cachedRs.setPageSize(pageSize); //使用ResultSet装填RowSet,设置从第几条记录开始 cachedRs.populate(rs, (page-1)*pageSize+1); } catch (SQLException e) { e.printStackTrace(); } return cachedRs; } public static void main(String[] args) throws SQLException { String sql = "select id,name,age from t_student "; TestCachedRowSet cp=new TestCachedRowSet(); CachedRowSet rs=cp.getRowset(sql, 3, 3); while(rs.next()){ System.out.println(rs.getInt("id")+"--"+rs.getString("name")+"--"+rs.getInt("age")); } } }