JDBC - SELECT

CHOISUJIN·2023년 1월 31일
0
post-thumbnail

1단계 : JDBC 참조 변수 선언

Connection conn = null;
Statement stmt = null;
ResultSet rs = null;

2단계 : 참조변수에 알맞은 객체 대입 --> try ~ catch문

// 1. DB연결에 필요한 Oracle JDBC Driver 메모리에 로드하기
Class.forName("oracle.jdbc.driver.OracleDriver"); //ClassNotFoundException

// 2. 연결 정보를 담은 Connection 생성
String type = "jdbc:oracle:thin:@";
String ip = "localhost";
String port = ":1521";
String sid = ":XE";
String user = "kh";
String pw = "kh1234";

conn = DriverManager.getConnection(type + ip + port + sid, user, pw);
//SQLException

System.out.println("<입력받은 급여보다 많이 받는(초과) 직원만 조회>");
System.out.print("급여 입력 : "); // InputMismatchException
int inputSalary = sc.nextInt();

3. SQL 작성
String sql = "SELECT EMP_ID, EMP_NAME, SALARY FROM EMPLOYEE WHERE SALARY > " + inputSalary;

4. Statement 객체 생성
stmt = conn.createStatement();

5. 생성된 Statement 객체에 sql을 적재하여 실행한 후 결과를 반환 받아와서 rs 변수에 저장
rs = stmt.executeQuery(sql); 

3단계 : SQL 수행해서 반환받은 결과(ResultSet)를 한 행씩 접근해서 컬럼값 얻어오기 --> try ~ catch문

while(rs.next()){
	String empId = rs.getString("EMP_ID");
    String empName = rs.getString("EMP_NAME");
    int salary = rs.getInt("SALARY");
    
	System.out.printf("사번 : %s / 이름 : %s / 급여 : %d\n", empId, empName, salary); 
}

4단계 : 사용한 JDBC 객체 자원 반환 ( close() ) --> finally

  • 생성 역순으로 닫아주기!
try {
	if(rs != null) rs.close();
    if(stmt != null) stmt.close();
    if(rs != null) rs.close();
    
} catch(SQLException e){
	e.printStackTrace();
    
}
profile
매일매일 머리 터지는 중 ᕙ(•̀‸•́‶)ᕗ

0개의 댓글