728x90
JDBC(Java DataBase Connectivity)는 자바 프로그램에서 관계형 데이터베이스를 연동하기 위해 제공하는 표준 API이다.
java.sql 패키지로 지원하며 JDBC(java.sql) API를 이용하면 DBMS에 종속되지 않고 프로그램 개발이 가능하다. (DB 전환이 쉬움)
JDBC가 특정 DB에 종속되지 않고 연동을 지원할 수 있는 이유는 JDBC API가 인터페이스를 기반으로 다형성을 이용하기 때문이다.
JDBC API가 제공하는 인터페이스를 구현한 클래스를 JDBC 드라이버라고 하는데 jar형태의 압축 파일로 제공되며 DB연동을 처리할 때 DB가 변경되더라도 JDBC 드라이버만 교체하면 프로그램의 수정 없이 DB를 변경할 수 있다.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class InsertUserTest {
public static void main(String[] args) {
// JDBC 관련 변수
Connection conn = null;
PreparedStatement stmt = null;
try {
/* JDBC 1단계 : 드라이버 객체 로딩 */
DriverManager.registerDriver(new org.h2.Driver());
/* JDBC 2단계 : 커넥션 연결 */
String jdbcUrl = "jdbc:h2:tcp://localhost/~/test";
// url이름, 접속 이름, 접속 비밀번호 순서로 입력하나보다. getConnection은 static 메서드임.
conn = DriverManager.getConnection(jdbcUrl, "sa", "");
/* JDBC 3단계 : Statement 생성 */
// 일반 statement는 sql injection 대처가 어려워 PreparedStatement를 사용함. values 암호화.
String sql = "insert into users values(?, ?, ?, ?)";
stmt = conn.prepareStatement(sql);
/* JDBC 4단계 : SQL 전송 */
// values ? 값 설정
stmt.setString(1, "testId");
stmt.setString(2, "testPassWord");
stmt.setString(3, "testName");
stmt.setString(4, "testRole");
// sql 전송
int count = stmt.executeUpdate();
System.out.println(count + "건 데이터 처리 성공!");
if (conn != null) {
System.out.println("H2 연결 성공 : " + conn.toString());
}
if (stmt != null) {
System.out.println("Statement 객체 : " + stmt.toString());
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
/* JDBC 5단계 : 연걸 해제 */
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
|
cs |

H2 DB.jar를 라이브러리 폴더에 넣어준 뒤
다음과 같이 JDBC를 이용해 H2 DB와 연동하였을 때
DriverManager 값을 변경하면 쉽게 DB를 전환할 수 있다.
Ex) 오라클로 ojdbc를 이용할 때
|
1
2
3
|
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:xe";
Connection conn = DriverManager.getConnection(url, "scott", "1111");
|
cs |
그러나 위처럼 코드를 작성하면 매번 데이터를 수정, 삭제 조회할 때마다 Connection 작업을 해야하는 번거로움이 있다.
그렇기 때문에 static 메서드를 활용하여 재사용 가능한 유틸을 만드는 것이 좋다.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
package com.test.common;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class JDBCUtil {
public static Connection getConnection() {
Connection conn = null;
try {
/* JDBC 1단계 : 드라이버 객체 로딩 */
DriverManager.registerDriver(new org.h2.Driver());
/* JDBC 2단계 : 커넥션 연결 */
String jdbcUrl = "jdbc:h2:tcp://localhost/~/test";
// url이름, 접속 이름, 접속 비밀번호 순서로 입력하나보다. getConnection은 static 메서드임.
conn = DriverManager.getConnection(jdbcUrl, "sa", "");
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public static void close(PreparedStatement stmt, Connection conn) {
/* JDBC 5단계 : 연결 해제 */
try {
stmt.close();
} catch(SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch(SQLException e) {
e.printStackTrace();
}
}
}
|
cs |
다음과 같이 재사용한 유틸 클래스를 만들어주면
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
package com.test.user;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.test.common.JDBCUtil;
public class InsertUserTest {
public static void main(String[] args) {
// JDBC 관련 변수
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = JDBCUtil.getConnection();
/* JDBC 3단계 : Statement 생성 */
// 일반 statement는 sql injection 대처가 어려워 PreparedStatement를 사용함. values 암호화.
String sql = "insert into users values(?, ?, ?, ?)";
stmt = conn.prepareStatement(sql);
/* JDBC 4단계 : SQL 전송 */
// values ? 값 설정
stmt.setString(1, "testId");
stmt.setString(2, "testPassWord");
stmt.setString(3, "testName");
stmt.setString(4, "testRole");
// sql 전송
int count = stmt.executeUpdate();
System.out.println(count + "건 데이터 처리 성공!");
if (conn != null) {
System.out.println("H2 연결 성공 : " + conn.toString());
}
if (stmt != null) {
System.out.println("Statement 객체 : " + stmt.toString());
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtil.close(stmt, conn);
}
}
}
|
cs |
INSERT문을 수행할 때, static 메소드를 활용하여 객체 구현 없이 DB연결과 해제를 수행할 수 있다.
코드가 간결해졌으며 재사용을 할 수 있게 됨
'WEB' 카테고리의 다른 글
| [WEB]Redirect와 Forward의 차이 (0) | 2024.02.15 |
|---|---|
| 이클립스 톰캣 resource '/server' does not exist 에러 해결 방법 (0) | 2024.02.15 |
| [WEB]VO 패턴 (VO Pattern) (0) | 2024.02.14 |
| [WEB]DAO 패턴 (DAO Pattern) (0) | 2024.02.14 |
| JSON과 XML (0) | 2024.02.14 |