본문 바로가기

.etc/Review

[211002] OracleConnect 복습

package com.db.conn;

import java.io.*;
import java.sql.*;
import java.util.*;
import oracle.jdbc.pool.OracleDataSource;

public class OracleConnect {
	private Properties info = new Properties();  
	private Connection conn = null;
	private Statement stat = null;
	private String query;

	//초기화 블럭으로 prop 파일 부르기 (주석 처리한 user 정보)
	{ 
		// 1. 데이터베이스 연결 구성 정보가 있는 파일 불러오기
		String userHome = System.getProperty("user.home");
		//사용자 홈 디렉토리를 문자열로 반환한 것. C:\Users\lmry 
		this.info.load(new FileReader(userHome + "/oracle_connection.prop"));
	}//초기화 블럭의 예외처리 던지고 싶다면 생성자에서 예외 던지면 된다.											//특문 \\oracle_도 가능. 단 2개쓰기 			
	/*
	 * Properties 객체를 활용하여 파일을 FileInputStream으로 읽고
	 * load 매소드를 활용하여 해당 파일을 읽어들입니다.
	 * properties 파일이 load 가 되면 getProperty 메소드를 통해서 해당 key의 value에 접근 할 수 있습니다. 
	 * ex) this.info.getProperty("cloud-url");
	 */
	
	/*
	 * Oracle Database 연결을 위한 과정
	 * 1. 데이터베이스 연결 구성 정보 생성
	 * 2. 연결 구성 정보로 데이터베이스 연결
	 * 3. 생성된 연결정보로 Statement 생성
	 * 4. 생성된 Statement로 Query 전송
	 * 5. ResultSet 받아서 필요한 내부 처리 진행
	 * 6. 모든 내부 처리 완료 후 자원 반납.(close 작업)
	 */
	public OracleConnect() throws Exception {
		this.connect();  //생성자에서 예외 던지면 초기화블럭 예외처리 던져진다
	}
	
	public OracleConnect(boolean wallet) throws Exception {
		if(wallet) {
			this.walletConnect();
		} else {
			this.connect();
		}
	}
	// wallet 정보로 데이터베이스 연결
	public void walletConnect() throws Exception {
		OracleDataSource ods = new OracleDataSource();
		ods.setURL(this.info.getProperty("cloud-url"));
		ods.setConnectionProperties(this.info);
		this.conn = ods.getConnection();
		this.stat = this.conn.createStatement();	
	}
	
	// 기본 정보로 데이터베이스 연결
	public void connect() throws Exception {
		Class.forName("oracle.jdbc.driver.OracleDriver");
		this.conn = DriverManager.getConnection(
				this.info.getProperty("local-url"),
				this.info.getProperty("user"),
				this.info.getProperty("password")
				);
		this.stat = this.conn.createStatement();	
	}

	// 실행한 SQL Query를 외부에서 설정하게 한다.
	public void setQuery(String query) {
		this.query = query;
	}

	// 설정된 SQL Query를 실행후 결과를 반환한다.
	public ResultSet execute() {
		ResultSet rs = null;	
		//만일 null이면 바로 반환 (null처리)
		if(this.query == null) {
			return rs;
		}
		
		try {
			rs = this.stat.executeQuery(this.query);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return rs;
	}
	
	public void close() throws SQLException {
		// 6. 모든 내부 처리 완료 후 자원 반납.(close 작업)
		this.stat.close();	// this.stat2.close();
		this.conn.close();	// this.conn2.close();
	} // 예외 던지면 Sample1 클래스의 close(); 실행하는 곳에서 처리 해주면 된다.
	
	public static void main(String[] args) {
		try {
			OracleConnect oc = new OracleConnect();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

 

public void connect() throws Exception {
		Class.forName("oracle.jdbc.driver.OracleDriver"); // 없어도 되는 구문.
		this.conn = DriverManager.getConnection(          // DriverManager.getConnection() 메소드 개선 되었기 때문
				this.info.getProperty("local-url"),
				this.info.getProperty("user"),
				this.info.getProperty("password")
				);
		this.stat = this.conn.createStatement();	
	}

 

JDBC(Java Database Connectivity)를 이용해서 데이터베이스에 연결해보신 적이 다들 있으실 겁니다.

데이터베이스에 연결하기 전에 각각의 데이터베이스에 맞는 드라이버를 로드해야 합니다.

드라이버를 로드하기 위해서 아래와 같이 Class 클래스의 forName 메소드를 사용하는 것은 모두 아실거라고 생각합니다.

Class.forName("oracle.jdbc.driver.OracleDriver");

(오라클드라이버를 로드하는 코드입니다. 사용하시는 각각의 데이터베이스에 맞게 괄호안을 채우셔야 합니다.)

 

이렇게 드라이버를 로드하고 나면 DriverManager.getConnection() 메소드와 URL을 이용해서 연결을 설정하게 되죠.

 

하지만 이제는 class.forName 메소드를 이용해서 드라이버를 로드할 필요가 전혀 없어졌습니다.

JDBC API 4.0부터 DriverManager.getConnection() 메소드가 개선되어 드라이버를 자동으로 로드하게 되었습니다. 

 

출처: https://endorphin0710.tistory.com/53