WEB/JAVA / / 2021. 11. 22. 21:38

[JDBC] DB 연동 클래스 생성

  • 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
반응형
  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유