实现分页

引用

package day03;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import tarena.util.DBUtil;

public class JDBCTest2 {
	public static void main(String[] args) throws Exception {
		test2(7000,10);
	}
	static void test2(int page, int pageSize) throws Exception {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			con = DBUtil.openInThread();
			page = page < 1?1:page;
			int start = (page-1) * pageSize + 1;
			int end = start + pageSize;
			// [start, end)
			pstmt = con.prepareStatement(
					"select * from  " +
					"(select t.*, rownum r from " +
					"(select * from s_emp) t) " +
					"where r >=? and r<?");
			pstmt.setInt(1, start);
			pstmt.setInt(2, end);
			rs = pstmt.executeQuery();
			while(rs.next()) {
				System.out.println(rs.getString("first_name"));
			}
		} finally {
			DBUtil.close(null, pstmt, rs);
			DBUtil.closeInThread();
		}
	}
	static void test1(int page, int pageSize) throws Exception {
		Connection con = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			con = DBUtil.openInThread();
			stmt = con.createStatement(
					ResultSet.TYPE_SCROLL_INSENSITIVE, 
					ResultSet.CONCUR_READ_ONLY);
			rs = stmt.executeQuery(
					"select * from s_emp");
			page = page < 1?1:page;
			int start = (page-1) * pageSize + 1;
			// 定位,返回值表示指针位置是否有数据
			boolean hasRow = rs.absolute(start); 
			// 如果指针指向没有数据的位置,不能取数据
			if(!hasRow || rs.isBeforeFirst() || rs.isAfterLast()) {
				System.out.println("指针位置无数据");
				return;
			}

			// 从此位置向后取出pageSize条数据
			for(int i=0;i<pageSize;i++) {
				System.out.println(rs.getString("first_name"));
				if(! rs.next()) { // 如果剩余数据不足,结束
					break;
				}
			}

		} finally {
			DBUtil.close(null, stmt, rs);
			DBUtil.closeInThread();
		}
	}
}



service类
package day03;

import java.util.ArrayList;
import java.util.List;
import day02.Emp;

public class EmpService {
	public void save(Emp emp) throws Exception {
	}
	public void delete(Emp emp) throws Exception {
	}
	public void update(Emp emp) throws Exception {
		// update s_emp set .... where id=?
	}	
	public Emp findById(int id) throws Exception {
		return null;
	}

	public List<Emp> findAll() throws Exception {
		List<Emp> list = new ArrayList<Emp>();
		/*rs = 执行查询;
		while(rs.next()) {
			从rs中一个数据一个数据的取出
			新建Emp对象
			将数据放入Emp对象
			Emp对象放入list
		}*/
		return list;
	}
	
	public List<Emp> findAll(int page, int pageSize) throws Exception {
        return null;	
	}

	

	public int findMaxPage(int pageSize) throws Exception {
		 return  0;	
	}
}


你可能感兴趣的:(java,sql)