본문 바로가기

콩's EDUCATION/콩's JAVA_RUN

SELECT rownum 정렬하기

rownum 정렬하기


 

import java.sql.*;
import java.sql.Date;
import java.util.*;


public class SelectPageTest {
 public static void main(String[] args) {
  Connection con = null;
  try{
  Class.forName("oracle.jdbc.driver.OracleDriver");
  // 사용할 드라이버 로드한다.
  con = DriverManager.getConnection
    ("jdbc:oracle:thin:@127.0.0.1:1521:xe","scott","tiger");
  System.out.println("정상적으로 연결 되었습니다. ");
  
 
  Scanner input = new Scanner(System.in);
  System.out.println("페이지를 입력하세요 : ");
  int in = input.nextInt();
  int start = (in-1)*5+1; //6
  int end = in*5;  //6

  String selectSql =
  
  "SELECT e2.*"
  +" FROM(SELECT rownum r, e1.*"
  +" FROM(SELECT * FROM emp ORDER BY sal desc nulls last) e1"
  +" )e2"
  +" WHERE r>="+start+" and r<="+end;
  

  // rownum 은 1 제외하고는 >, >= 연산이 불가능하다.
  
  // SQL 전송 결과 검색
  Statement st = con.createStatement();
  ResultSet rs = st.executeQuery(selectSql);
  int count = 0;
  while(rs.next()==true){
   int r = rs.getInt("r");
   int empno = rs.getInt("empno");
   System.out.println(r+":"+empno);
   String ename = rs.getString("ename");
   String job = rs.getString("job");
   int mgr = rs.getInt("mgr");
   Date d = rs.getDate("hiredate");
   double sal = rs.getDouble("sal");
   double comm = rs.getDouble("comm");   
   int deptno = rs.getInt("deptno");
   System.out.println(
     r+":"+empno+":"+ename+":"+job+":"+mgr+":"+d+":"
     +":"+sal+":"+comm+":"+deptno);
   count++;
  }
  System.out.println("데이터 갯수="+count);
  con.close();
  System.out.println("정상적으로 연결해제 되었습니다.");
  con.close();
  System.out.println("정상적으로 연결해제 되었습니다.");
  }catch(ClassNotFoundException e){
   System.out.println ("jdbc 드라이버 미등록이거나 이름 오류입니다.");
  }catch(SQLException e){
   e.printStackTrace();
   System.out.println("연결정보 오류");
  }finally{
   try{
   if(!con.isClosed()) con.close();
   }catch(SQLException e){
    System.out.println("finally 오류");
   }
  }
 }
}

 

 


 

SelectPageTest.java