//个人学习用、如涉及到版权请联系博主
1.加载驱动
2.连接数据库
3.创建ResultSet
4.创建CacheRowSet
5.设置并获取分页数据
6.执行查询,展示数据
// 实现分页效果
public
CachedRowSet
query
(String sql,
int
pageSize,
int
page)
throws
Exception{
// 加载驱动
Class.forName(driver);
try
(
// 获取数据库连接
Connection conn = DriverManager.getConnection(url,user,pass);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)){
RowSetFactory factory = RowSetProvider.newFactory();
CachedRowSet cachedRs= factory.createCachedRowSet();
// 设置每页显示pageSize条记录
cachedRs.setPageSize(pageSize);
// 设置从第几条记录开始
cachedRs.populate(rs,(page - 1) * pageSize + 1);
return cachedRs;
}
}
// 主函数
public
static
void
main
(String[] args)
throws
Exception{
// 有了它就不要写Catch了
CachedRowSetPage cp =
new
CachedRowSetPage();
cp.initParam();
CachedRowSet rs = cp.query(
"select * from tp_goods"
, 3, 4);
while
(rs.next()) {
System.out.println(rs.getString(1) +
"\t"
+ rs.getString(4) +
"\t"
+ rs.getString(5));
}
}