고급 JAVA
JAVA-JDBC - 외부 properties
햄찌개
2020. 9. 29. 18:48
외부의 properties 파일을 읽어와 Properties객체로 처리하기
public class T03_PropertiesTest {
public static void main(String[] args) {
//읽어온 정보를 저장할 Properties객체 생성
Properties prop = new Properties();
//읽어올 파일명을 이용한 File객체 생성
File file = new File("res/db.properties");
try {
//파일 읽기를 수행할 FileInputSteam객체 생성
FileInputStream fis = new FileInputStream(file);
//Properties객체로 파일 내용읽기
//파일의 내용을 읽어와 key와 value값으로 분류한 후 Properties객체에 담아준다
prop.load(fis);
//읽어온 자료를 출력하기
//key값만 읽어와 Enumeration 객체로 반환한다.
Enumeration<String> keys =(Enumeration<String>)prop.propertyNames();
//key값 개수 만큼 반복해서 값 출력하기
//keys.hasMoreElement()
// => 다음 포인터 위치에 자료가 있으면 true, 없으면 false 반환함.
while (keys.hasMoreElements()) {
String key = keys.nextElement();
String value = prop.getProperty(key);
System.out.println(key+" => "+value);
}
System.out.println("출력끝...");
} catch (IOException e) {
e.printStackTrace();
}
}
}
db.properties
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521/xe
user=JEON
pass=java
JDBCUtill.java
/**
* JDBC 드라이버를 로딩하고 Connection객체를 생성하는 메서드 제공
*/
public class JDBCUtill {
static {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("드라이버 로딩 완료 ...");
} catch (ClassNotFoundException e) {
System.out.println("드라이버 로딩 실패 ...");
}
}
public static Connection getConnection() {
try {
return DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521/xe",
"JEON",
"java");
} catch (SQLException e) {
System.out.println("DB 연결 실패...");
return null;
}
}
/**
* 자원 반납하는 메서드
* @param conn
* @param stmt
* @param pstmt
* @param rs
*/
public static void disConnect(Connection conn, Statement stmt, PreparedStatement pstmt, ResultSet rs) {
if(rs!=null)try {rs.close();}catch (SQLException ex) {ex.printStackTrace();}
if(stmt!=null)try {stmt.close();}catch (SQLException ex) {ex.printStackTrace();}
if(pstmt!=null)try {pstmt.close();}catch (SQLException ex) {ex.printStackTrace();}
if(conn!=null)try {conn.close();}catch (SQLException ex) {ex.printStackTrace();}
}
}