๐Ÿ‘พJDBC Util ๋งŒ๋“ค๊ธฐ

HCยท2022๋…„ 9์›” 15์ผ
1
post-thumbnail

Java๋ฅผ ์ด์šฉํ•ด ์˜ค๋ผํด DB์— ์—ฐ๊ฒฐํ•ด์ฃผ๋Š” JDBC๋ฅผ ๊ณต๋ถ€ํ•˜๋‹ค๋ณด๋ฉด
ํ•ญ์ƒ ๋™์ผํ•˜๊ฒŒ ์ž…๋ ฅํ•ด์ค˜์•ผํ•˜๋Š” ์ฝ”๋“œ๋“ค์ด ์žˆ๋‹ค.

  • ์˜ค๋ผํด ๋“œ๋ผ์ด๋ฒ„ ๋กœ๋”ฉ
    Class.forName("oracle.jdbc.driver.OracleDriver");
  • DB ์—ฐ๊ฒฐ
    Connection conn = DriverManager.getConnction("์ฃผ์†Œ,ํฌํŠธ๋ฒˆํ˜ธ","๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์•„์ด๋””","๋น„๋ฐ€๋ฒˆํ˜ธ");

๐Ÿ˜Ž ํŽธํ•˜๊ฒŒ ๊ฐ€์ž.

๋งค๋ฒˆ ๋˜‘๊ฐ™์€ ์ž‘์—…์„ ๋ฐ˜๋ณตํ•˜๊ธฐ์—” ๋„ˆ๋ฌด ๊ท€์ฐฎ์œผ๋‹ˆ๊นŒ Util class๋ฅผ ํ•˜๋‚˜ ๋งŒ๋“ค์–ด๋ณด์ž.

์•„๋ž˜์˜ ์ฝ”๋“œ๋ฅผ ๋ณด์ž.


JDBC Util

package kr.or.ddit.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

//JDBC ๋“œ๋ผ์ด๋ฒ„๋ฅผ ๋กœ๋”ฉํ•˜๊ณ  Connection ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๋Š” ๋ฉ”์„œ๋“œ๋กœ ๊ตฌ์„ฑ๋œ class ๋งŒ๋“ค๊ธฐ
public class DBUtil {
	static { 
		try {
        	//๋“œ๋ผ์ด๋ฒ„ ๋กœ๋”ฉ
			Class.forName("oracle.jdbc.driver.OracleDriver");
            
		} catch (ClassNotFoundException e) {
			// TODO: handle exception
			System.out.println("๋“œ๋ผ์ด๋ฒ„ ๋กœ๋”ฉ ์‹คํŒจ");
			e.printStackTrace();
		}
	}
	
	public static Connection getConnection() {
		try {
			return DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "DB์•„์ด๋””", "๋น„๋ฐ€๋ฒˆํ˜ธ");
			
		} catch (SQLException e) {
        
			System.out.println("DB ์—ฐ๊ฒฐ ์‹คํŒจ");
			return null; //try์™€ catch ๋ชจ๋‘์—์„œ ๋ฐ˜ํ™˜๊ฐ’์ด ์žˆ์–ด์•ผํ•จ
		}
		
	}
}

์ด๋ ‡๊ฒŒ ๋งŒ๋“ค์–ด๋†“์€ util ํด๋ž˜์Šค๋Š”

๋‹ค๋ฅธ ํด๋ž˜์Šค์—์„œ ์ด๋ ‡๊ฒŒ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.
์ € ์ฝ”๋“œ ํ•œ์ค„๋กœ ๋“œ๋ผ์ด๋ฒ„ ๋กœ๋”ฉ๊ณผ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์™€์˜ ์—ฐ๊ฒฐ์€ ๋์ด๋‹ค.


์ด util ํด๋ž˜์Šค์—์„œ๋Š” close ๊ธฐ๋Šฅ์„ ๋„ฃ์ง„ ์•Š์•˜์ง€๋งŒ util ํด๋ž˜์Šค์— close() ๋ฉ”์„œ๋“œ๋ฅผ ๋งŒ๋“ค์–ด๋ณธ๋‹ค๋ฉด,

์ด๋Ÿฐ์‹์œผ๋กœ ํ™œ์šฉํ•˜๋ฉด finally ๋ธ”๋ก์„ ๋งŒ๋“ค์ง€ ์•Š์•„๋„ ๋˜๋Š” ์ด์ ์ด ์žˆ๋‹ค.

profile
์˜ค๋ฅ˜๋ณด๊ณ 

1๊ฐœ์˜ ๋Œ“๊ธ€

comment-user-thumbnail
2022๋…„ 9์›” 15์ผ

๊ตณ์žก์ด์‹œ๋„ค์š”๐Ÿ˜Ž

๋‹ต๊ธ€ ๋‹ฌ๊ธฐ