// 필드
private static Connection conn = null;
// 왜 static 필드?
// - static 메서드가 참조 가능한 필드는 static 필드 밖에 없기 때문에
public static Connection getConnection() {
try {
// 커넥션 객체가 없거나 닫혀있는 경우
// -> 새로운 연결(커넥션 다시 얻어오기)
if(conn == null || conn.isClosed()) {
// conn.isClosed() : 커넥션이 close 상태이면 true 반환
Properties prop = new Properties();
// Map<String, String> 형태, XML 파일 입출력 특화
prop.loadFromXML( new FileInputStream("driver.xml") );
// 스트림을 이용해서 driver.xml 파일을 읽어와 prop에 저장
// prop에 저장된 값을 변수로 따로 저장
String driver = prop.getProperty("driver");
String url = prop.getProperty("url"); // key값
String user = prop.getProperty("user");//key값
String pw = prop.getProperty("pw");//key값
// Oracle JDBC Driver 객체 메모리 로드
Class.forName(driver);
// DriverManager를 이용해 Connection 얻어오기
conn = DriverManager.getConnection(url, user, pw);
// ** 자동 커밋 비활성화 ** //
// -> 왜? 개발자가 직접 트랜잭션을 제어하기 위해서
conn.setAutoCommit(false);
}
}catch (Exception e) {
e.printStackTrace();
}
return conn;
}
Connection 생성
Connection conn = getConnection();
JDBCTemplete에서 커넥션이 기존에 없었거나 닫혀있었으면
Properties prop = new Properties(); 라는
Map<String,String> 형태의 객체를
스트림을 이용해서 외부에 있는 “driver.xml” 파일을 읽어와서
prop.loadFromXML( new FileInputStream("driver.xml") );
** driver.xml에는 <key,value>형태로 세팅이 되어있다.**
<entry key="driver">oracle.jdbc.driver.OracleDriver</entry>
<entry key="url">jdbc:oracle:thin:@115.9*.21*.22:9000:XE</entry>
<entry key="user"**_***</entry>
<entry key="pw">oracle_******</entry>
prop에 저장한다.
String driver = prop.getProgerty(“driver”);
String url = prop.getProperty(“url”);
String user = prop.getProperty(“user”);
String pw = prop.getProperty(“pw”);)
**prop에 저장된 값을 변수로 따로 저장하는 과정**
prop에 저장 후 새로운 connection 객체를 만들어서
conn = DriverManager.getConnection(url, user, pw);
conn 값을 반환하는 메서드이다.
return conn;