자바로 페이징을 하는 것도 결국 SQL문에서 페이징 코드를 잘 작성하여 구현해내면 된다.
페이징에 대해 개념이 잘 잡혀있지 않다면 아래의 글을 참조해보는 것도 좋다.
참조 : https://ddcloud.tistory.com/90
[Oracle] #5-3 rownum으로 페이징하기
1. 모조칼럼 rownum rownum은 #4-3에서 간단한 개념을 알아보았었다. https://ddcloud.tistory.com/84 [Oracle] #4-3 Oracle 함수 : nvl, 모조칼럼(rownum, rowid) 1. nvl() 함수 이 함수는 마리아DB에서 if..
ddcloud.tistory.com
위의 코드를 바탕으로 페이징 코드도 자바로 구현시킬 수 있다.
코드만 보면 복잡해보이고 이해안될 수 있으니 페이징의 개념과 셀프 조인의 개념을 이해한 후 코드를 살펴보기를 바라는 마음이다.
package jdbc0922;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Test07_selectPaging {
public static void main(String[] args) {
// 페이징
// 문제) sungjuk 테이블에서 이름 순으로 정렬한 후 행번호 4~6행만 조회하시오
int start = 4;
int end = 6;
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
String url = "jdbc:oracle:thin:@localhost:1521:xe"; // == "127.0.0.1"
String user = "system";
String password = "1234";
String driver = "oracle.jdbc.driver.OracleDriver"; // ojdbc6.jar
Class.forName(driver);
con = DriverManager.getConnection(url, user, password);
System.out.println("오라클DB 서버 연결 성공!!");
StringBuilder sql = new StringBuilder();
sql.append(" select rnum, sno, uname, kor, eng, mat, tot, aver, addr, wdate ");
sql.append(" from ( ");
sql.append(" select sno, uname, kor, eng, mat, tot, aver, addr, wdate, rownum as rnum ");
sql.append(" from ( ");
sql.append(" select sno, uname, kor, eng, mat, tot, aver, addr, wdate ");
sql.append(" from sungjuk ");
sql.append(" order by uname ");
sql.append(" ) AA ");
sql.append(" ) BB ");
sql.append(" where rnum>=? and rnum<=?");
pstmt = con.prepareStatement(sql.toString());
pstmt.setInt(1, start);
pstmt.setInt(2, end);
rs= pstmt.executeQuery();
if(rs.next()) {
System.out.println("자료 있음");
do {
System.out.print(rs.getInt("rnum") + " ");
System.out.print(rs.getInt("sno") + " ");
System.out.print(rs.getString("uname") + " ");
System.out.print(rs.getInt("kor") + " ");
System.out.print(rs.getInt("eng") + " ");
System.out.print(rs.getInt("mat") + " ");
System.out.print(rs.getInt("tot") + " ");
System.out.print(rs.getInt("aver") + " ");
System.out.print(rs.getString("addr") + " ");
System.out.print(rs.getString("wdate") + " ");
System.out.println();
} while(rs.next()); // end
} else {
System.out.println("자료 없음");
} // if end
} catch (Exception e) {
System.out.println("오라클DB 연결 실패 : " + e);
} finally {
// 자원 반납
try {
if(rs!=null) {rs.close();}
} catch (Exception e) {}
try {
if(pstmt!=null) {rs.close();}
} catch (Exception e) {}
try {
if(con!=null) {rs.close();}
} catch (Exception e) {}
}// end
System.out.println("뚱");
} // main() end
} // class end
'⁂ Java > : JDBC - Java DataBase Connectivity' 카테고리의 다른 글
[JAVA] JDBC #2-2 CRUD(Create, Read, Update, Delete) : R (1) | 2022.09.22 |
---|---|
[JAVA] JDBC #2-1 CRUD(Create, Read, Update, Delete) : C,U,D (1) | 2022.09.21 |
[JAVA] JDBC #1 - 환경 구축하기 (0) | 2022.09.21 |