[자바] Java DB

[공부]/컴퓨터 | 2011. 4. 26. 04:05
Posted by 주야양
반응형

개인적으로 달력을 보완하고 있는데 양력-음력 변환을 위하여 DB를 사용하기로 했다.
기존 SmallSQL의 경우 자료가 많아지면 속도가 현저히 떨어지는 문제가 있어 여러가지 DB를 시험중이다.

<Java DB 개요>
Java DB는 자바로 만들어진 라이트웨이트 DBMS이다.
아파치 더비(Apache Derby)는 Java DB의 핵심기술이다.
현재 Sun에서 지원하고 있다. (Java 6버전의 릴리스를 시작으로, Sun은 JDK에 Java DB를 패키지 하기 시작했다.)

JavaDB의 특징은 Apache Derby의 특징과 같다.
1. base engine과 JDBC driver 모두 합쳐 2메가바이트
2. 자바와 JDBC, SQL을 기초로 만들어짐
3. client/server 모드를 Derby Network Client JDBC driver and Derby Network Server를 통해 지원 가능
4. 설치 및 디플로이, 사용이 편함

또한 JavaDB는 다음과 같은 환경에 적합하다고 소개되어 있다.
- 자바 애플리케이션 개발 및 테스트, 임베디드 애플리케이션, 멀티 플랫폼 환경, Web 2.0 기반의 브라우져 based 환경, PDA와 같이 J2ME CDC에서 돌아가는 애플리케이션

<Java DB 설치 및 DB 생성>
1. Java DB를 다운로드 받아 설치한다.
   ☞ http://www.oracle.com/technetwork/java/javadb/downloads/index.html
   단, 이미 Java SE(JDK 6)이 설치되어 있으면 이미 C:\Program Files\Sun\JavaDB 경로에 설치되어 있다.

2. 환경변수를 셋팅한다. JDK 설치시 이미 설치되어 있으므로 아래와 같이 설정한다. 
   - DERBY_HOME => C:\Program Files\Sun\JavaDB
   - Path                 => %DERBY_HOME%\bin;
   만약, 다운로드 받아 설치했다면, 매뉴얼의 DERBY_HOME =>c:\Derby_10, Path => %DERBY_HOME%\bin로 한다.

3. DB 생성 (실행 > cmd)

C:\Users\Administrator>cd %DERBY_HOME%
C:\Program Files\Sun\JavaDB\bin>ij
ij 버전 10.4
ij> connect 'jdbc:derby:juya_calendar;create=true';
ij> create table juya_calendar(num INT, yyyy INT, mm INT, dd INT, lyyyy INT,lmm INT, ldd INT, holiday varchar(100), memo varchar(100));
0행이 삽입됨/갱신됨/삭제됨
ij> select * from juya_calendar;
NUM        |YYYY       |MM         |DD         |LYYYY      |LMM      |LDD      |HOLIDAY      |MEMO
---------------------------------------------------------------------------------------------
0행이 선택되었습니다.
ij> exit;
C:\Program Files\Sun\JavaDB\bin>

- Java DB(Derby)가 설치된 위치의 bin 하위에 DB가 생성된다.
  (내 경우는 'C:\Program Files\Sun\JavaDB\bin\juya_calendar')

4. 자바 프로그램에서의 사용은 SimpleApp 로 대체한다.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class SimpleApp
{
   
/* the default framework is embedded*/
   
public String framework = "embedded";
   
public String driver = "org.apache.derby.jdbc.EmbeddedDriver";
   
public String protocol = "jdbc:derby:";

   
public static void main(String[] args)
   
{
       
new SimpleApp().go(args);
   
}

   
void go(String[] args)
   
{
       
/* parse the arguments to determine which framework is desired*/
        parseArguments
(args);

       
System.out.println("SimpleApp starting in " + framework + " mode.");

       
try
       
{
           
/*
               The driver is installed by loading its class.
               In an embedded environment, this will start up Derby, since it is not already running.
             */

           
Class.forName(driver).newInstance();
           
System.out.println("Loaded the appropriate driver.");

           
Connection conn = null;
           
Properties props = new Properties();
            props
.put("user", "user1");
            props
.put("password", "user1");

           
/*
               The connection specifies create=true to cause
               the database to be created. To remove the database,
               remove the directory derbyDB and its contents.
               The directory derbyDB will be created under
               the directory that the system property
               derby.system.home points to, or the current
               directory if derby.system.home is not set.
             */

            conn
= DriverManager.getConnection(protocol +
                   
"derbyDB;create=true", props);

           
System.out.println("Connected to and created database derbyDB");

            conn
.setAutoCommit(false);

           
/*
               Creating a statement lets us issue commands against
               the connection.
             */

           
Statement s = conn.createStatement();

           
/*
               We create a table, add a few rows, and update one.
             */

            s
.execute("create table derbyDB(num int, addr varchar(40))");
           
System.out.println("Created table derbyDB");
            s
.execute("insert into derbyDB values (1956,'Webster St.')");
           
System.out.println("Inserted 1956 Webster");
            s
.execute("insert into derbyDB values (1910,'Union St.')");
           
System.out.println("Inserted 1910 Union");
            s
.execute(
               
"update derbyDB set num=180, addr='Grand Ave.' where num=1956");
           
System.out.println("Updated 1956 Webster to 180 Grand");

            s
.execute(
               
"update derbyDB set num=300, addr='Lakeshore Ave.' where num=180");
           
System.out.println("Updated 180 Grand to 300 Lakeshore");

           
/*
               We select the rows and verify the results.
             */

           
ResultSet rs = s.executeQuery(
                   
"SELECT num, addr FROM derbyDB ORDER BY num");

           
if (!rs.next())
           
{
               
throw new Exception("Wrong number of rows");
           
}

           
if (rs.getInt(1) != 300)
           
{
               
throw new Exception("Wrong row returned");
           
}

           
if (!rs.next())
           
{
               
throw new Exception("Wrong number of rows");
           
}

           
if (rs.getInt(1) != 1910)
           
{
               
throw new Exception("Wrong row returned");
           
}

           
if (rs.next())
           
{
               
throw new Exception("Wrong number of rows");
           
}

           
System.out.println("Verified the rows");

            s
.execute("drop table derbyDB");
           
System.out.println("Dropped table derbyDB");

           
/*
               We release the result and statement resources.
             */

            rs
.close();
            s
.close();
           
System.out.println("Closed result set and statement");

           
/*
               We end the transaction and the connection.
             */

            conn
.commit();
            conn
.close();
           
System.out.println("Committed transaction and closed connection");

           
/*
               In embedded mode, an application should shut down Derby.
               If the application fails to shut down Derby explicitly,
               the Derby does not perform a checkpoint when the JVM shuts down, which means
               that the next connection will be slower.
               Explicitly shutting down Derby with the URL is preferred.
               This style of shutdown will always throw an "exception".
             */

           
boolean gotSQLExc = false;

           
if (framework.equals("embedded"))
           
{
               
try
               
{
                   
DriverManager.getConnection("jdbc:derby:;shutdown=true");
               
}
               
catch (SQLException se)
               
{
                    gotSQLExc
= true;
               
}

               
if (!gotSQLExc)
               
{
                   
System.out.println("Database did not shut down normally");
               
}
               
else
               
{
                   
System.out.println("Database shut down normally");
               
}
           
}
       
}
       
catch (Throwable e)
       
{
           
System.out.println("exception thrown:");

           
if (e instanceof SQLException)
           
{
                printSQLError
((SQLException) e);
           
}
           
else
           
{
                e
.printStackTrace();
           
}
       
}

       
System.out.println("SimpleApp finished");
   
}

   
static void printSQLError(SQLException e)
   
{
       
while (e != null)
       
{
           
System.out.println(e.toString());
            e
= e.getNextException();
       
}
   
}

   
private void parseArguments(String[] args)
   
{
       
int length = args.length;

       
for (int index = 0; index < length; index++)
       
{
           
if (args[index].equalsIgnoreCase("jccjdbcclient"))
           
{
                framework
= "jccjdbc";
                driver
= "com.ibm.db2.jcc.DB2Driver";
                protocol
= "jdbc:derby:net://localhost:1527/";
           
}
           
if (args[index].equalsIgnoreCase("derbyclient"))
           
{
                framework
= "derbyclient";
                driver
= "org.apache.derby.jdbc.ClientDriver";
                protocol
= "jdbc:derby://localhost:1527/";
           
}
       
}
   
}
}

앗, 속도의 문제가......
나만 느린건가......




반응형
 

블로그 이미지

주야양

소소한 일상에 대한 기록

카테고리

Juyayang's hiStory (492)
[가상화폐(암호화폐)] (114)
[정보] (29)
[리뷰] (7)
[여행] (72)
[취미] (37)
[공부] (23)
[결혼] (18)
[임신 및 출산] (86)
[육아] (34)
[KOICA] (41)
[일상 생활] (20)
[자료실] (7)