자바

고급 자바_0106-1

정재화니 2023. 1. 6. 13:52

JDBC를 이용한 DB자료를 처리해보겠습니다.

 

- 처리 순서
  1. 드라이버 로딩 ==> JDBC라이브러리를 사용할 수 있도록 메모리에 읽어 들이는 작업
  (JDBC API 버전 4.0이상에서는 getConnection()메서드에서 자동으로 로딩해주기 때문에 
  이 부분을 생략할 수 있다.↓↓↓ 그렇지만 우리는 생략하지 않고 사용할 예정임...
  Class.forName("orcale.jdbc.driver.OracleDriver");
 
  2. DB에 접속하기 ==> 접속이 완료되면 Connection객체가 반환된다.
  DriverManager.getConnection()메서드를 이용한다.
 
  3. 질의 ==> SQL문장을 DB서버로 보내서 결과를 얻어온다.
  (Statement객체나 PreparedStatement객체를 이용하여 작업한다.)
 
  4. 결과 처리 ==> 질의 결과를 받아서 원하는 작업을 수행한다.
  1) SQL문이 select문일때 ==> select한 결과가 ResultSet객체에 저장되어 반환된다.
  2) SQL문이 select문이 아닐때(insert, update, delete 등) ==> 작업 결과가 정수값으로 반환된다.
  (반환되는 정수값은 해당 작업에 성공한 레코드 수를 의미한다.)
 
  5. 사용했던 자원 반납하기 ==> 각 자원의 close()메서드 이용

 


public class JdbcTest01 {

	public static void main(String[] args) {
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		
		try {
			// 1. 드라이버 로딩
			Class.forName("oracle.jdbc.driver.OracleDriver");
			
			// 2. DB연결 ==> Connection객체 생성
			conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "JJH96","****");
			
			// 3. 질의
			
			// 3-1. SQL문 작성하기
//			String sql = "select * from lprod";
			String sql = "select lprod_id, lprod_gu, lprod_nm nm from lprod";
			
			// 3-2. Statement객체 또는 PreparedStatement객체 생성 ==> Connection객체 이용
			stmt = conn.createStatement();
			
			// 3-3. SQL문을 DB서버로 보내서 결과를 얻어온다.
			// 		==> 실행할 SQL문이 select문이기 때문에 처리 결과가 ResultSet객체에 저장되어 반환된다.
			rs = stmt.executeQuery(sql);
			
			// 4. 결과 처리 ==> 한 레코드씩 출력하기
			
			System.out.println(" == 쿼리문 처리 결과 ==");
			// ResultSet객체의 데이터를 차례로 꺼내오려면 반복문과 next()메서드를 이용하여 처리한다.
			
			// rs.next() ==> ResultSet객체의 데이터를 가리키는 포인터를 다음번째 위치로 이동시키고 
			// 				 그 곳에 데이터가 있으면 true, 없으면 false를 반환한다.
			
			while(rs.next()) {
				// 포인터가 가리키는 곳의 데이터 가져오기
				// 형식1) rs.get자료형이름("컬럼명 또는 Alias명") ==> 컬럼명과 Alias명은 대소문자 구분없이 사용가능
				// 형식2) rs.get자료형이름(컬럼번호)	==> 컬럼번호는 1번부터 시작
				System.out.println("Lprod_id : " + rs.getInt("lprod_id"));
				System.out.println("Lprod_gu : " + rs.getString(2));
				System.out.println("Lprod_nm : " + rs.getString("nm"));
			}
			
			
			
			
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			// 5. 자원 반납
			if(rs != null) try { rs.close(); } catch(SQLException e) {}
			if(stmt != null) try { stmt.close(); } catch(SQLException e) {}
			if(conn != null) try { conn.close(); } catch(SQLException e) {}
			
		}
		
	}

}

DB를 연결하고 실행하면 

 

자료를 출력할 수 있다.


예제문제를 풀어보자 

문제) 사용자로부터 Lprod_id값을 입력 받아서 입력한 값보다 Lprod_id가 큰 자료들을 출력하시오.

public class JdbcTest02 {

	public static void main(String[] args) {
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		Scanner sc = new Scanner(System.in);
		
		
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			
			conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "JJH96","****");
			
			System.out.print("Lprod_id값을 입력하세요? ");
			String str = sc.nextLine(); 
//			int str = sc.nextInt(); 
			
			String sql = " select * from lprod "
						  + " where lprod_id > " + str ;
			
			stmt = conn.createStatement();
			
			rs = stmt.executeQuery(sql);
			
			while(rs.next()) {
				System.out.println("Lprod_id : " + rs.getInt("lprod_id"));
				System.out.println("Lprod_gu : " + rs.getString(2));
				System.out.println("Lprod_nm : " + rs.getString("lprod_nm"));
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			if(rs != null) try { rs.close(); } catch(SQLException e) {}
			if(stmt != null) try { stmt.close(); } catch(SQLException e) {}
			if(conn != null) try { conn.close(); } catch(SQLException e) {}
		}
		
	}

}

결과

 

6번보다 큰 lprod_id만 나오는 것을 볼 수 있다.


이번에는 Lprod_id 값을 2개 입력 받아서 두 값 중 작은 값부터 큰 값 사이의 자료들을 출력해 보겠습니다.

 

public class JdbcTest03 {

	public static void main(String[] args) {
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		Scanner sc = new Scanner(System.in);
		
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			
			conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "JJH96", "****");
			
			int temp;
			int input1; 
			int input2;
			
			System.out.print("값을 입력 하세요 >> ");
			input1 = sc.nextInt();
			System.out.print("값을 입력 하세요 >> ");
			input2 = sc.nextInt();
			
			if(input1 > input2) {
				
				temp = input1;
				input1 = input2;
				input2 =temp;
			}
			
			String sql = " select * from lprod "  
					+ " where lprod_id > " + input1 + "and lprod_id < " + input2;
			
			stmt = conn.createStatement();
			
			rs = stmt.executeQuery(sql);
			
			System.out.println("=== 처리 결과 ===");
			
			while(rs.next()) {
				System.out.println("Lprod_id : " + rs.getInt("lprod_id"));
				System.out.println("Lprod_gu : " + rs.getString(2));
				System.out.println("Lprod_nm : " + rs.getString("lprod_nm"));
				System.out.println("---------------------------------------------");
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}finally {
			if(rs != null) try { rs.close(); } catch(SQLException e) {}
			if(stmt != null) try { stmt.close(); } catch(SQLException e) {}
			if(conn != null) try { conn.close(); } catch(SQLException e) {}
		}
	}
}

결과:

작은 값과 큰 값의 사이의 Lprod_id가 나오는 것을 알 수 있다.