- DB 연동을 쉽고 편리하게 하기위해 Class로 선언
- 해제를 위해 마지막에 DBConn.close 메서드 실행 필수
DBConn 클래스 소스코드
package com.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
// single ton
public class DBConn {
private DBConn() {}
private static Connection connection = null;
public static Connection getConnection() {
if( connection == null ) {
// 1. JDBC Driver 로딩 - Class.forName()
String className = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String user = "scott";
String password = "tiger";
try {
Class.forName(className);
// 2. Connection = DriverManager.getConnection()
// Connection 객체를 얻어온다
connection = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
} //if
return connection;
}// getConnection
// 오버로딩
public static Connection getConnection(String url, String user, String password) {
if( connection == null ) {
// 1. JDBC Driver 로딩 - Class.forName()
String className = "oracle.jdbc.driver.OracleDriver";
try {
Class.forName(className);
// 2. Connection = DriverManager.getConnection()
// Connection 객체를 얻어온다
connection = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
} //if
return connection;
}// getConnection
public static Connection getConnection(String serverName, int port, String sid, String user, String password) {
if( connection == null ) {
// 1. JDBC Driver 로딩 - Class.forName()
String className = "oracle.jdbc.driver.OracleDriver";
String url = String.format("jdbc:oracle:thin:@%s:%d:%s", serverName, port, sid);
try {
Class.forName(className);
// 2. Connection = DriverManager.getConnection()
// Connection 객체를 얻어온다
connection = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
} //if
return connection;
}// getConnection
public static void close() {
try {
// 4. 연결닫기
if ( connection != null && !connection.isClosed() ) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
connection = null; // ***
}
} //class
반응형
'Backend > JAVA' 카테고리의 다른 글
[JAVA] List 출력 "System.out::println" (0) | 2022.05.20 |
---|---|
[이클립스] 편집창 세로줄 없애는 방법 (0) | 2021.12.02 |
[JAVA] 컬렉션 클래스 정리 & 요약 (0) | 2021.10.06 |
[JAVA] Properties 컬렉션 클래스 (0) | 2021.10.05 |
[JAVA] HashMap과 Hashtable (0) | 2021.10.05 |