본문 바로가기

Code/Java

경량 DBMS 사용하기

데이터처리하는 프로그램을 작성하다보면, 데이터베이스를 이용하면 좀 더 간편하게 해결되는 문제들을 접하게 된다. 이런 경우에 DB 사용을 고려하지만, 설치 및 배포의 문제로 인하여(간단한 배치프로그램을 위해서 서버에 계정만들고, DB만들어서 자료처리하는 것이 번거롭다는 것), 경량 DB (보통 file기반 DB)라는 대안을 찾게 되었다.

물론 최근에 아이폰 개발 책을 보면서, 데이터처리를 위해서 sqlite를 쓴다는 것을 보면서, 간단한 프로그램을 만들때도 경량 DB를 임베드하는 형태로 개발하면 좋겠구나 생각이 들었다.

자바에서 이용할 수 있는 경량 DB로 sqlite를 염두해두고 googling를 했는데, Derby라는 아파치 프로젝트의 산출문이 더 낫다는 의견을 접할 수 있었다. 이에 간단하게 코드를 작성해 보았는 데, 별 문제 없이 임베드하는 데 성공하였다.

JDBC를 이용하기 때문에 사용법은 일반적인 사용법과 동일하고, 설정부분만 보면, 다음 코드와 같다.
(코드는 apache 홈페이지에 튜토리얼에 있는 내용을 정리하여 코드화한 것이다.)

public class DerbyManager {
String driver = "org.apache.derby.jdbc.EmbeddedDriver";
String dbName="jdbcDemoDB";
String connectionURL = "jdbc:derby:" + dbName + ";create=true";


DerbyManager(String argDbName) {
dbName = argDbName;
String driver = "org.apache.derby.jdbc.EmbeddedDriver";
try {
   Class.forName(driver); 
} catch(java.lang.ClassNotFoundException e) {
e.printStackTrace();
}
}
Connection getConnection() {
Connection conn = null;
String connectionURL = "jdbc:derby:" + dbName + ";create=true";
try {
conn = DriverManager.getConnection(connectionURL);
} catch (Throwable e) {
e.printStackTrace();
}
return conn;
}
void close() {
if (driver.equals("org.apache.derby.jdbc.EmbeddedDriver")) {
boolean gotSQLExc = false;
try {
DriverManager.getConnection("jdbc:derby:;shutdown=true");
} catch (SQLException se) {
if (se.getSQLState().equals("XJ015")) {
gotSQLExc = true;
}
}
if (!gotSQLExc) {
System.out.println("Database did not shut down normally");
} else {
System.out.println("Database shut down normally");
}
}
}
static void errorPrint(Throwable e) {
if (e instanceof SQLException)
SQLExceptionPrint((SQLException) e);
else {
System.out.println("A non SQL error occured.");
e.printStackTrace();
}
} // END errorPrint

// Iterates through a stack of SQLExceptions
static void SQLExceptionPrint(SQLException sqle) {
while (sqle != null) {
System.out.println("\n---SQLException Caught---\n");
System.out.println("SQLState:   " + (sqle).getSQLState());
System.out.println("Severity: " + (sqle).getErrorCode());
System.out.println("Message:  " + (sqle).getMessage());
sqle.printStackTrace();
sqle = sqle.getNextException();
}
} // END SQLExceptionPrint
}

* 참고목록