jdbc CallableStatement 存储过程 实现 SQL SERVER分页
SQL Server的分页可以有几种方式实现,例如最简单的:1、select top 20 * from table where id not in(select top 200 id from table where ?)即取20条记录,并且这些记录是不在当前页的之前的那些页的记录中。这个方式比较简单,但破坏SQL的可读性,并且当你的该SQL语句有很多的过滤条件时,显得特别恶心了,例如 select top pagesize from table where id not in(select top pagesize * (curPage - 1) id from table where create_date > 'aaaa' and create_date < 'aaaaa' and....) and create_date > 'aaaa' and create_date < 'aaaaa' and.......。如果你的程序本身已经已经有了大量的JDBC操作sql语句,那现在突然让你加一个分页的功能,。
2、用后台SQL SERVER的存储过程来实现分页:
CREATE procedure pageProcedure
@sqlstr nvarchar(4000), --查询字符串
@currentpage int, --第N页
@pagesize int, --每页行数
@out_row_count int output,--输出总行数
@out_page_count int output--输出总页数
as
set nocount on
declare @P1 int, --P1是游标的id
@rowcount int
exec sp_cursoropen @P1 output,@sqlstr,@scrollopt=1,@ccopt=1,@rowcount=@rowcount output
--select ceiling(1.0*@rowcount/@pagesize) as 总页数,@rowcount as 总行数,@currentpage as 当前页
set @out_row_count = @rowcount
set @out_page_count = ceiling(1.0*@rowcount/@pagesize)
set @currentpage=(@currentpage-1)*@pagesize+1
exec sp_cursorfetch @P1,16,@currentpage,@pagesize
exec sp_cursorclose @P1
set nocount off
GO
调用
declare @row_count int
declare @page_count int
exec pageProcedure 'select * from employees', 1, 200, @row_count, @page_count
现在看如果我们用JDBC如何读取返回的数据:
CallableStatement callableStatement = this.getDatabase().getConnection().prepareCall("{call pageProcedure(?,?,?,?,?)}");
callableStatement.setString(1, this.getCurSQL());//IN
callableStatement.setInt(2, this.curPage);//IN
callableStatement.setInt(3, this.countPerPage); //IN
callableStatement.registerOutParameter(4, Types.INTEGER);//OUT
callableStatement.registerOutParameter(5, Types.INTEGER); //OUT
callableStatement.execute();
int r = 0;
//返回ResultSet
while(callableStatement.getMoreResults())
{
ResultSet set = callableStatement.getResultSet();
if(set != null)
{
//处理ResultSet 又回到原来的处理模式,如果这一块包装的话,对原来的代码影响小,
set.close();
}
}
这里的情况是如果有大量的这样sql语句的时候,这种模式对代码的修改比较少。如果较少的就不说。
页:
[1]