天天看點

oracle的分頁

之前學習oracle時,寫的一個分頁語句,是對emp表做的分頁,為了加深記憶以及友善以後的查詢使用,現将語句記錄如下:

public List<Emp> queryEmpAllOnRownum(int pageNum) {
		String sql = "select em.*  from " +
				"(select rownum rn,e.* from (select * from emp order by deptno) e "+
			"where rownum <= ?) em where em.rn>= ?";
	
		//擷取記錄的總條數
		int countRow = new EmpServiceImpl().queryCountEmp();//此處需要重新建立對象調用,否則會出現無效的列類型
		int pages=(int)(Math.ceil(countRow*1.0/pageSize));//總頁數
		//如果目前頁小于第一頁,就為第一頁
		if(pageNum<1){
			pageNum =1;
		System.out.println("頁數不能小于第一頁");	
		}	
		//如果目前頁大于最後一頁,就為最後一頁
		if(pageNum>pages){
			pageNum =pages;
			System.out.println("頁數不能大于最大頁,最大頁為:"+pages);	
		}
		int start = (pageNum-1)*pageSize+1;
		int end = pageNum!=pages?(start+pageSize-1):countRow;
		
		String[] params ={end+"",start+""};
		List<Emp> list = new ArrayList<Emp>();
		
		try {
			this.open(sql);
			this.exeSelect(params);
			while(rs.next()){
				Integer empno = rs.getInt("empno");
				String ename = rs.getString("ename");
				String job = rs.getString("job");
				Integer mgr = rs.getInt("mgr");
				Date hiredate = rs.getDate("hiredate");
				Double sal = rs.getDouble("sal");
				Double comm = rs.getDouble("comm");
				Integer deptno = rs.getInt("deptno");
				Emp emp = new Emp(empno,ename,job,mgr,hiredate,sal,comm,deptno);
				list.add(emp);
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			this.close();
		}
		return list;
	}

	//擷取記錄的總條數
	public int queryCountEmp() {
		String sql = "select count(*) from emp";
		int i=0;
		try { 
			this.open(sql);  
			rs = this.exeSelect(null);
			while(rs.next()){
				i = rs.getInt(1);
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			this.close();
		}
		return i;
	}
           

比較簡單的一個分頁語句,有别的需求也可以通過這個文法變形去添加!