JDBC(Java Database Connectivity)는 자바에서 데이터베이스와 상호작용하기 위한 표준 API입니다. 데이터베이스 연결 설정을 관리할 때 Properties 객체를 사용하면 더 유연하고 유지보수하기 쉬운 코드 작성을 할 수 있습니다. Properties 객체는 키-값 쌍으로 구성된 데이터를 저장할 수 있는 자바의 내장 클래스입니다.
JDBC에서 Properties 사용
JDBC에서 Properties 객체를 사용하면 데이터베이스 연결을 설정하는 데 필요한 속성을 좀 더 간편하게 관리할 수 있습니다. 일반적으로 DriverManager.getConnection 메서드를 사용할 때 Properties 객체를 전달합니다.
1. 기본적인 사용 방법
Properties 객체 생성 및 설정
다음은 Properties 객체를 생성하고 데이터베이스 연결에 필요한 속성을 설정하는 예제입니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class JDBCPropertiesExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
Properties properties = new Properties();
properties.setProperty("user", "myuser");
properties.setProperty("password", "mypassword");
properties.setProperty("useSSL", "false");
try (Connection connection = DriverManager.getConnection(url, properties)) {
System.out.println("Database connected!");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
|
cs |
2. 외부 파일을 사용한 설정
Properties 객체를 외부 파일에서 로드하여 사용할 수도 있습니다. 이는 설정 정보를 코드에서 분리하여 보안 및 유지보수성을 향상시킬 수 있습니다.
설정 파일 생성
다음과 같이 db.properties 파일을 생성합니다.
1
2
3
4
|
user=myuser
password=mypassword
useSSL=false
|
cs |
외부 파일에서 Properties 객체 로드
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
|
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class JDBCPropertiesFileExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
Properties properties = new Properties();
try (FileInputStream input = new FileInputStream("db.properties")) {
properties.load(input);
} catch (IOException e) {
e.printStackTrace();
}
try (Connection connection = DriverManager.getConnection(url, properties)) {
System.out.println("Database connected!");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
|
cs |
3. JDBC Properties 객체의 주요 속성
일반적으로 Properties 객체를 사용하여 설정하는 속성에는 다음과 같은 것들이 있습니다.
- user: 데이터베이스 사용자 이름
- password: 데이터베이스 사용자 비밀번호
- useSSL: SSL 사용 여부 (예: true 또는 false)
- autoReconnect: 자동 재연결 설정 (예: true 또는 false)
- characterEncoding: 문자 인코딩 설정 (예: UTF-8)
4. 예외 처리 및 리소스 관리
데이터베이스 연결 시 예외 처리 및 리소스 관리를 철저히 해야 합니다. try-with-resources 문을 사용하면 자원을 자동으로 해제할 수 있어 코드의 안전성을 높일 수 있습니다.
예외 처리 및 리소스 관리 예제
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
|
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class JDBCPropertiesExceptionHandling {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
Properties properties = new Properties();
try (FileInputStream input = new FileInputStream("db.properties")) {
properties.load(input);
} catch (IOException e) {
System.err.println("Failed to load properties file: " + e.getMessage());
return;
}
try (Connection connection = DriverManager.getConnection(url, properties)) {
System.out.println("Database connected!");
} catch (SQLException e) {
System.err.println("Failed to connect to the database: " + e.getMessage());
}
}
}
|
cs |
5. 고급 설정
특정 데이터베이스 드라이버는 추가적인 설정을 지원합니다. 예를 들어, MySQL의 경우 다음과 같은 설정을 사용할 수 있습니다.
- serverTimezone: 서버의 타임존 설정
- allowPublicKeyRetrieval: 공개 키 검색 허용 설정 (보안 관련)
MySQL 고급 설정 예제
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class JDBCMysqlAdvancedProperties {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
Properties properties = new Properties();
properties.setProperty("user", "myuser");
properties.setProperty("password", "mypassword");
properties.setProperty("useSSL", "false");
properties.setProperty("serverTimezone", "UTC");
properties.setProperty("allowPublicKeyRetrieval", "true");
try (Connection connection = DriverManager.getConnection(url, properties)) {
System.out.println("Database connected!");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
|
cs |
결론
JDBC에서 Properties 객체를 사용하는 것은 데이터베이스 연결 설정을 유연하고 간편하게 관리할 수 있는 강력한 방법입니다. 이를 통해 코드의 가독성과 유지보수성을 높일 수 있습니다. 외부 파일을 사용하여 설정을 분리하면 보안과 관리 측면에서 큰 이점을 얻을 수 있습니다.
'DATABASE 공부' 카테고리의 다른 글
Trigger (0) | 2024.08.02 |
---|---|
SQL의 DATA LANGUAGE (0) | 2024.08.02 |
Template (0) | 2024.08.01 |
PL/SQL (0) | 2024.07.31 |
관계형 데이터베이스 (0) | 2024.07.31 |