1. 程式人生 > >結合JDBC和Oracle ROWNUM實現分頁查詢

結合JDBC和Oracle ROWNUM實現分頁查詢

這兩天興趣大發,突然想複習一下JDBC對資料庫的操作,剛好一個同事問我:Oracle如何實現分頁查詢?基於此前提,就將二者結合複習。

首先,對於oracle的分頁,本人熟練的目前有兩種,這兩種都還是結合網上各位同行的經驗而掌握的。

我們知道:rownum是oracle根據你查詢的結果給每行自動虛擬新增的一個行號。

第一種:利用rownum和between and進行分頁

select * from(select rownum as rn, t.* from table_name t) temp where temp.rn between 0 and 1000;

這就可以查詢出0到1000行的結果;

第二種:利用rownum和三層查詢模式進行分頁

select * from (select rownum as rn, t.* from table_name t where rownum<2000) temp where temp.rn>1000;

這可以查詢到1000到2000行的資料

針對上面兩種sql語句:我們可以結合jdbc實現分頁:請看程式碼:

首先新建UDUtil.java,用於獲得Connection,以及定義一些常量:

package org.cmcc.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.log4j.Logger;

/**
 * @Desc 		資料庫連線工具類
 * @Author 		Administrator
 * @Datetime 	2012-9-24下午06:07:10
 * @Version 	1.0
 */
public class DBUtil {
	private static Logger logger = Logger.getLogger(DBUtil.class);
	
	//資料庫連線資訊:資料庫驅動、主機地址:埠:例項、使用者名稱、密碼
	public static String db_driver = "oracle.jdbc.driver.OracleDriver";
	public static String db_url = "jdbc:oracle:thin:@localhost:1521:ORCL";
	public static String db_user = "gd";
	public static String db_password = "gd123";
	
	//每頁多少行
	public static final int pageSize = 10000;
	
	/**
	 * 獲得資料庫連線
	 * @param driver
	 * @param url
	 * @param user
	 * @param password
	 * @return
	 */
	public static Connection getConnection() {
		Connection conn = null;
		try {
			Class.forName(db_driver);
			conn = DriverManager.getConnection(db_url, db_user, db_password);
		} catch (ClassNotFoundException e) {
			logger.error("資料庫驅動載入失敗!", e);
		} catch (SQLException e) {
			logger.error("連線資料庫失敗!", e);
		}
		
		return conn;
	}
	
}

第二步:建立一個數據庫操作類:DBDAO.java
package org.cmcc.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.cmcc.entity.DGwap201208;
import org.cmcc.util.DBUtil;
/**
 * @Desc 		資料庫操作類
 * @Author 		Administrator
 * @Datetime 	2012-9-24下午05:50:37
 * @Version 	1.0
 */
public class DGwapDAO {
	private static Logger logger = Logger.getLogger(DGWapDAO.class);
	
	private Connection conn = null;
	
	private Statement stm = null;
	
	private ResultSet rs = null;
	
	/**
	 * 分頁獲得資料
	 * @param pageNum	頁碼
         * @param pageSize      每頁多少行
         * @return
	 */
	public List<DGwap201208> getGdWapByPage(int pageNum, int pageSize) {
		List<DGwap201208> results = new ArrayList<DGwap201208>();;
		DGwap201208 wap = null;
		
		int start = pageSize * pageNum;
		int end = pageSize * (pageNum + 1);
		
		//分頁查詢語句:利用ROWNUM
		String sql = "SELECT * FROM (SELECT ROWNUM AS rn, T.MSISDN as msisdn,T.USER_AGENT as userAgent," +
				"T.URL as url,T.USE_TIME as useTime,T.STATUS_CODE as statusCode," +
				"T.DOWN_TRAFFIC as downTraffic,T.UP_TRAFFIC as upTraffic," +
				"T.GETWAY_DELAY as getwayDelay,T.SP_DELAY as spDelay " +
				"FROM DG_WAP_201208 T) WHERE rn>=" + start + " AND rn<" + end;
                
               /*String sql = "SELECT * FROM (SELECT ROWNUM AS rn, T.MSISDN as msisdn,T.USER_AGENT as userAgent," +
		"T.URL as url,T.USE_TIME as useTime,T.STATUS_CODE as statusCode," +
		"T.DOWN_TRAFFIC as downTraffic,T.UP_TRAFFIC as upTraffic," +
		"T.GETWAY_DELAY as getwayDelay,T.SP_DELAY as spDelay " +
		"FROM DG_WAP_201208 T) WHERE rn BETWEEN " + start + " AND " + end;*/

                long startTime = System.currentTimeMillis();
		logger.info("執行第" + (pageNum + 1) + "次分頁查詢!當前毫秒時間是:" + System.currentTimeMillis());
		logger.info("JDBC分頁查詢語句:" + sql.toString());
		try {
			conn = DBUtil.getConnection();
			stm = conn.createStatement();
			
			rs = stm.executeQuery(sql);
			
			while(rs.next()) {
				wap = new DGwap201208();
				
				wap.setMsisdn(rs.getString("msisdn"));
				wap.setUserAgent(rs.getString("userAgent"));
				wap.setUrl(rs.getString("url"));
				wap.setUseTime(rs.getString("useTime"));
				wap.setStatusCode(rs.getString("statusCode"));
				wap.setDownTraffic(Long.valueOf(rs.getString("downTraffic")));
				wap.setUpTraffic(Long.valueOf(rs.getString("upTraffic")));
				wap.setGetwayDelay(Long.valueOf(rs.getString("getwayDelay")));
				wap.setSpDelay(Long.valueOf(rs.getString("spDelay")));
				
				results.add(wap);
			}
		} catch (SQLException e) {
			logger.error("分頁獲取資料失敗!", e);
		} finally {
			this.closeResouce();
		}
		long endTime = System.currentTimeMillis();
		logger.info("第" + (pageNum + 1) + "次將分頁查詢結果返回!" + "當前毫秒時間是:" + System.currentTimeMillis());
		logger.info("本次獲取 " + DBUtil.pageSize + "條資料,消耗時間:" + (endTime - startTime)/1000 + " 秒");
		return results;
	}
	
	/*public static void main(String[] args) {
		DGWapDao wapDao = new DGWapDAO();
		System.out.println(wapDao.getGdWapByPage(0).size());
	}*/
	
        /*
         *關閉連線,釋放資源
         */
        public void closeResouce() {
		logger.info("開始關閉資源連線,以釋放空間...");
		try {
			if(rs != null) {
				rs.close();
			}
			if(stm != null) {
				stm.close();
			}
			if(conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			logger.error("關閉連線失敗!", e);
		}
	}
}


第三步:測試,分頁資料的正確性:PageData.java

package org.cmcc.http;

import java.util.List;

import org.cmcc.dao.DGWapDAO;
import org.cmcc.entity.DGwap201208;

/**
 * @Desc 		測試
 * @Author 		Administrator
 * @Datetime 	2012-9-26下午04:37:41
 * @Version 	1.0
 */
public class PageDataTest {
	public static void main(String[] args) {
		DGWapDAO wapDao = new DGWapDAO();
		List<DGwap201208> results = wapDao.getGdWapByPage(1, 10);
		for(DGwap201208 wap : results) {
			System.out.println(wap.getMsisdn() + " | " + wap.getStatusCode() + " | " + wap.getUrl().substring(1, 20) + "... | " +wap.getUserAgent() + " | " + wap.getUseTime() + " | " + wap.getDownTraffic()+ " | " + wap.getUpTraffic()+ " | " + wap.getGetwayDelay()+ " | " + wap.getSpDelay());
		}
	}
}

這樣基本實現分頁查詢資料的目的了。

由於本人是個java菜鳥,所有,程式碼和思路上難以有瑕疵,歡迎各位拍磚指正!