本文主要谈谈Java调用SQL Server分页存储的过程,其返回是多个结果集,只要呈现形式是代码,文字不多,简单易懂。
SQL存储过程:
USE[Db_8za8za_2] GO SETANSI_NULLSON GO SETQUOTED_IDENTIFIERON GO –============================================= –Description:<Description,,通用分页存储过程> –============================================= ALTERPROCEDURE[dbo].[paging] –Addtheparametersforthestoredprocedurehere –传入参数 @SqlStrnvarchar(4000),–查询字符串 @CurrentPageint,–第N页(当前页数) @PageSizeint–每页行数 AS BEGIN –SETNOCOUNTONaddedtopreventextraresultsetsfrom –interferingwithSELECTstatements. SETNOCOUNTON; –定义变量 DECLARE@CursorIdint–CursorId是游标的id DECLARE@Rowcountint–总记录(行)数 DECLARE@pageCountint–总页数 –Insertstatementsforprocedurehere EXECsp_cursoropen@CursorIdoutput,@SqlStr, @Scrollopt=1,@Ccopt=1,@Rowcount=@RowcountOUTPUT SET@pageCount=CEILING(1.0*@Rowcount/@PageSize)–设置总页数 SELECT@pageCount AS总页数,@RowcountAS总行数,@CurrentPageAS当前页–提示页数 IF(@CurrentPage>@pageCount)–如果传入的当前页码大入总页码数则把当前页数设为最后一页 BEGIN SET@CurrentPage=@pageCount–设置当前页码数 END IF(@CurrentPage<=0)–如果传入的当前页码大入总页码数则把当前页数设为第一页 BEGIN SET@CurrentPage=1–设置当前页码数 END SET@CurrentPage=(@CurrentPage-1)*@PageSize+1–设置当前页码数 EXECsp_cursorfetch@CursorId,16,@CurrentPage,@PageSize EXECsp_cursorclose@CursorId–关闭游标 SETNOCOUNTOFF END
Java调用储存过程:
packagetest; importjava.sql.*; publicclassStudy3{ privateConnectioncon; publicResultSetrs; privateCallableStatementcallsta; privateStringuse="sa"; privateStringpwd="sa"; publicStudy3(){ try{ //连接数据库驱动 Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); Stringstr="jdbc:microsoft:sqlserver://localhost:1433;databasename=test"; con=DriverManager.getConnection(str,use,pwd); //设置存储过程参数 Stringst="{callPaging(?,?,?)}"; callsta=con.prepareCall(st); callsta.setString(1,"select*fromT_employee"); callsta.setInt(2,1); callsta.setInt(3,3); //循环输出调用存储过程的记录结果 StringBuffersb=newStringBuffer(); intrsNum=0;//统计结果集的数量 intupdateCount=-1; booleanflag=callsta.execute();//这个而尔值只说明第一个返回内容是更新计数还是结果集。 do{ updateCount=callsta.getUpdateCount(); if(updateCount!=-1){//说明当前行是一个更新计数 //处理. System.out.println("..说明当前行是一个更新计数.."); callsta.getMoreResults(); continue;//已经是更新计数了,处理完成后应该移动到下一行 //不再判断是否是ResultSet } rs=callsta.getResultSet(); if(rs!=null){//如果到了这里,说明updateCount==-1 //处理rs rsNum++; System.out.println("统计结果集的数量:"+rsNum); if(rs!=null){ ResultSetMetaDatarsmd=rs.getMetaData();//获取字段名 intnumberOfColumns=rsmd.getColumnCount();//获取字段数 inti=0; while(rs.next()){//将查询结果取出 for(i=1;i<=numberOfColumns;i++){ //System.out.println(rs.getInt("总页数")); Stringdate=rs.getString(i); sb.append(date+""); } } rs.close(); } callsta.getMoreResults(); continue; //是结果集,处理完成后应该移动到下一行 } //如果到了这里,说明updateCount==-1&&rs==null,什么也没的了 System.out.println(sb.toString()); }while(!(updateCount==-1&&rs==null)); //callsta.getXXX(int);//获取输出参数 }catch(Exceptione){ e.printStackTrace(); } } publicstaticvoidmain(String[]age){ Study3study=newStudy3(); } }
走一个地方停一个地方。在我心里最美好的就是和你一起老在路上,