2008. 7. 26. 16:10

JDBC PreparedStatement를 이용한 데이터 조회 예제

1. DataInsert_Prepared.java

01  import java.sql.*;
02  
03  public class DataInsert_Prepared{
04    Connection con = null;
05   PreparedStatement  ptmt = null;
06    
07   public static void main (String args [])  {
08     DataInsert_Prepared di = new DataInsert_Prepared();
09     try{
10      di.connect();
11      di.insert();
12     di.close();
13    }catch(SQLException e){
14     e.printStackTrace();
15    }finally{
16     try{
17      if(di.ptmt != null) di.ptmt.close();
18      if(di.con != null) di.con.close();
19     }catch(SQLException e){}
20    }    
21   }
22  
23   public void connect()throws SQLException {
24    try{
25     Class.forName("oracle.jdbc.driver.OracleDriver");
26     con = DriverManager.getConnection
27     ("jdbc:oracle:thin:@127.0.0.1:1521:ora9",
28     "jdbc00","jdbc00");
29     System.out.println("데이터베이스 연결되었습니다.");
30             }catch(ClassNotFoundException e){
31             System.out.println("JDBC Driver load fail!!!");
32                   }
33          }
34  
35   public void close()throws SQLException {
36    con.close();
37    System.out.println("데이터베이스 연결해제되었습니다.");
38  }
39  
40   public void insert()throws SQLException {
41    String query = "insert into emp values(?,?,?,?,?)";
42    ptmt = con.prepareStatement (query);
43    
44    int id = 8;
45    String name = "박삼성";
46    double bonus = 40000.00;
47    Date in_date = new Date(System.currentTimeMillis());
48    String dept = "인사부";
49    
50    ptmt.setInt(1,id);
51    ptmt.setString(2,name);
52    ptmt.setDouble(3,bonus);
53    ptmt.setDate(4,in_date);
54    ptmt.setString(5,dept);
55    int rowcount = ptmt.executeUpdate();
56  
57    id++;
58    name = "이자바";
59    dept = "총무부";
60    
61    ptmt.setInt(1,id);
62    ptmt.setString(2,name);
63    ptmt.setDouble(3,bonus);
64    ptmt.setDate(4,in_date);
65    ptmt.setString(5,dept);
66    rowcount += ptmt.executeUpdate();
67    
68    System.out.println
69 ("emp 테이블에" + rowcount +
70 " 개의 데이터가 삽입되었습니다.");
71    ptmt.close();
72   }
73  } 

2. DataSelect_Prepared.java

01  import java.sql.*;
02  
03  public class DataSelect_Prepared{
04    Connection con = null;
05   PreparedStatement  ptmt = null;
06    
07   public static void main (String args [])  {
08     DataSelect_Prepared dsp = new DataSelect_Prepared();
09     if(args.length < 2){
10      System.out.println
11      ("emp 테이블에서 조회할 id 값을 입력하세요.\n"
12           + "5번에서 8번까지의 id를 가진 데이터를 조회하려면\n"
13           + "java DataSelect_Prepared 5 8 을 입력하세요.");
14      return;
15    }
16    int start = Integer.parseInt(args[0]);
17    int end = Integer.parseInt(args[1]);
18    
19     try{
20      dsp.connect();
21     dsp.select(start, end);
22     dsp.close();
23    }catch(SQLException e){
24     e.printStackTrace();
25    }finally{
26     try{
27      if(dsp.ptmt != null) dsp.ptmt.close();
28      if(dsp.con != null) dsp.con.close();
29     }catch(SQLException e){}
30    }    
31   }
32  
33   public void connect() throws SQLException {
34    try{
35     Class.forName("oracle.jdbc.driver.OracleDriver");
36     con = DriverManager.getConnection
37     ("jdbc:oracle:thin:@127.0.0.1:1521:ora9",
38     "jdbc00","jdbc00");
39     System.out.println("데이터베이스 연결되었습니다.");
40            }catch(ClassNotFoundException e){
41            System.out.println("JDBC Driver load fail!!!");
42                 }
43   }
44  
45   public void close() throws SQLException {
46    con.close();
47    System.out.println("\n데이터베이스 연결해제되었습니다.");
48   }
49  
50   public void select(int start, int end) throws SQLException {
51    String query =
52    "select * from emp where id >= ? and id <= ?";
53    ptmt = con.prepareStatement (query);
54    
55    ptmt.setInt(1, start);
56    ptmt.setInt(2, end);
57      
58    ResultSet rs = ptmt.executeQuery();
59    System.out.println("조회 결과는 다음과 같습니다.\n");
60    while(rs.next()){
61     int id = rs.getInt("id");
62     String result = "ID : " + id + "\t";
63     String name = "이름 : " + rs.getString(2) + "\t";
64     result += name;
65     double bonus = rs.getDouble(3);
66     result += "BONUS : " + bonus + "\t";
67     Date inDate = rs.getDate(4);
68     result += "입사일 : " + inDate + "\t";
69     String dept = "부서 : " + rs.getString(5) + "\t";
70     result += dept;
71     System.out.println(result);
72    }     
73    ptmt.close();
74   }
75  } 

3. ImgTableCreate.java

01  import java.sql.*;
02  
03  public class ImgTableCreate{
04    Connection con = null;
05   Statement  stmt = null;
06    
07   public static void main (String args [])  {
08     ImgTableCreate tc = new ImgTableCreate();
09     tc.connect();
10     tc.createTable();
11     tc.close();
12   }
13  
14  public void connect(){
15    try{
16     Class.forName("oracle.jdbc.driver.OracleDriver");
17     con = DriverManager.getConnection
18     ("jdbc:oracle:thin:@127.0.0.1:1521:ora9",
19     "jdbc00","jdbc00");
20     System.out.println("데이터베이스 연결되었습니다.");
21            }catch(ClassNotFoundException e){
22            System.out.println("JDBC Driver load fail!!!");
23                  }catch(SQLException e){
24             System.out.println("Connection fail!!!");
25             e.printStackTrace();
26                 }
27  }
28  
29   public void close(){
30    try{
31     con.close();
32     System.out.println
33     ("데이터베이스 연결 해제되었습니다.");
34    }catch(SQLException e){
35     System.out.println("Connection fail!!!");
36     e.printStackTrace();
37    }finally{
38     try{
39      if(con != null) con.close();
40     }catch(SQLException e){}
41    }
42   }
43  
44   public void createTable(){
45     try{
46      stmt = con.createStatement ();
47      String query = "CREATE  TABLE img ";
48      query += "(name     VARCHAR2(30) , ";
49      query += " contents  RAW(2000))" ;
50      int rowcount = stmt.executeUpdate(query);
51      System.out.println
52      ("img 테이블 생성이 완료되었습니다.");
53      stmt.close();
54     }catch(SQLException e){
55      e.printStackTrace();
56     }finally {
57      try{
58       if(stmt != null) stmt.close();
59      }catch(SQLException e){}
60     }
61   }
62  } 

4. ImgTableInsert.java

01  import java.sql.*;
02  import java.io.*;
03  
04  public class ImgTableInsert {
05    public static void main (String args [])  {
06    Connection conn=null;
07    PreparedStatement pstmt=null;
08    try{
09     Class.forName ("oracle.jdbc.driver.OracleDriver");
10    }catch(ClassNotFoundException e){}
11  
12    try{
13     conn = DriverManager.getConnection
14     ("jdbc:oracle:thin:@127.0.0.1:1521:ora9",
15     "jdbc00","jdbc00");
16     pstmt = conn.prepareStatement
17     ("insert into img values (?,?)");
18     File  file = new File("anyboy.gif");
19     int size = (int) file.length();
20     FileInputStream fin = new FileInputStream(file);
21                   byte [] contents = new byte[size];
22                   int total;
23     while((total = fin.read(contents)) != -1){
24     }
25     pstmt.setString(1,file.getName());
26     pstmt.setBytes(2,contents);
27     int row  = pstmt.executeUpdate();
28     System.out.println
29     (row + " 개의 데이터가 삽입되었습니다");
30    }catch(Exception e){
31     e.printStackTrace();
32    }finally{
33                            if(pstmt != null) pstmt.close();
34                            if(conn != null) conn.close();
35                     }
36   }
37  } 



5. ImgTableSelect.java


01  import java.sql.*;
02  import java.io.*;
03  
04  public class ImgTableSelect {
05    public static void main (String args [])  {
06    Connection conn = null;
07    PreparedStatement pstmt = null;
08    FileOutputStream fout = null;
09    byte [] db = null;
10    
11    
12    try{
13     Class.forName ("oracle.jdbc.driver.OracleDriver");
14    }catch(ClassNotFoundException e){}
15  
16    try{
17     conn = DriverManager.getConnection
18     ("jdbc:oracle:thin:@127.0.0.1:1521:ora9",
19     "jdbc00","jdbc00");
20     pstmt = conn.prepareStatement
21     ("select contents from img where name = ?");
22     pstmt.setString(1,"anyboy.gif");
23    
24     int leng = (int)(new File("anyboy.gif").length());
25     db = new byte[leng];
26    
27     ResultSet rs = pstmt.executeQuery();
28     while(rs.next()){
29      db = rs.getBytes(1);
30     }
31    
32     fout = new FileOutputStream("anyboy.gif.db");
33     fout.write(db);
34     System.out.println
35     ("anyboy.gif.db 라는 파일에 저장했습니다\n");
36    }catch(Exception e){
37     e.printStackTrace();
38    }finally{
39                            if(pstmt != null) pstmt.close();
40                            if(conn != null) conn.close();
41                     }
42   }
43  } 





 

2008. 7. 26. 13:26

비스타에서 CHM 파일을 볼 수 있게 하는 프로그램



사용자 삽입 이미지

xCHM v1.13

비스타에서 보안 탓에 CHM 파일을 볼 수 없는 경우 이 프로그램을 이용하면 볼 수 있다.
그외에도 폰트를 변경할 수 있어 XP에서도 사용해도 좋을 것 같음.
File 메뉴에서 chm 의 기본 프로그램으로 등록하는 명령어가 있음.

출처 : http://thx4alice.tistory.com/59
원저작자 : http://xchm.sourceforge.net/

만약 위 프로그램으로 파일 열기 실패시 %Windows\ 폴더 밑에 HH.exe 파일을 연결해 주면 됨.

2008. 7. 24. 22:14

JDBC DataSource 인터페이스

1. DriverManager를 통한 Connection 생성의 단점

DriverManager를 통하여 Connection 생성하는 JDBC PROGRAM은 사용하려는 데이터베이스가 변경되거나 그에 따른 JDBC 드라이버가 변경된다면 JDBC PROGRAM의 소스에도 변경되어야 하는 정보가 있음.

JDBC 드라이버 이름과 JDBC URL, 데이터베이스 계정, 데이터베이스 암호등

2. DataSource 인터페이스의 역할

개발자가 어플리케이션 내에서 직접 하드 코딩하지 않으므로 투명한 개발 가능

getConnection 메서드를 이용해 Connection 객체를 생성하는데 이때 접근하는 데이터 소스가 달라도 코드의 수정은 없고, DataSource의 속성값(property)만 변경하여 적용할 수 있음.

DataSource는 JNDI(Java Naming & Directory Interface) 서비스를 제공하는 환경에서 사용 가능

JNDI를 이용한 DataSource를 이용하게 되면 다음과 같은 이점이 있음

*. JDBC PROGRAM 내에서 데이터베이스를 연결할 때에 JDBC 드라이버를 등록할 필요 없음
*. JDBC URL을 몰라도 JDBC 네이밍 서비스와 디렉토리 서비스가 제공하는 기능을 사용할 수 있음

3. DataSource 이용을 위한 Tomcat 엔진의 환경 설정

연결할 데이터베이스의 JDBC 드라이버를 Tomcat 엔진이 설치된 디렉토리의 common\lib 디렉토리에 존재해야 한다. 이 때 JDBC 드라이버 파일은 반드시 확장자 jar 형태로 압축되어 있어야 한다. Tomcat 에서 실행하는 JSP를 통하여 oracle 데이터베이스 9.2.0.1 에 연결하기 위해서는 oracle 데이터베이스 9.2.0.1용의 JDBC 드라
이버를 Tomcat 엔진이 인식하는 classpath로 설정된 디렉토리에 존재해야 한다.

*. http://127.0.0.1:8080/admin 접속한 후 admin 계정으로 로그 인
*. Tomcat Server > Service (Catalina) > Host(loalhost) > Context(/jdbc) > Data Sources 항목 클릭
*. Create New Data Source 클릭
*. 각 Property 입력

Property Value 비고
..JNDI Name ..jdbc/myoracle  
..Data Source URL ..jdbc:oracle:thin:@DB IP:1521:sid ..DB IP:접속하는 DB의 IP를 지정 sid :
..접속하는 DB의 sid
..JDBC Driver
..Class
..oracle.jdbc.driver.OracleDriver ..DB에 접속하기 위해 사용할 JDBC
..드라이버명
..User Name ..DB user name ..DB에 접속하기 위한 User Name
..Password ..DB password
..DB에 접속하기 위한 Password
..Max. Active
..Connections
..10 ..동시에 서비스할 수 있는 최대 활성화
.. 커넥션의 수
..Max. Idle
..Connections
..5 ..최대 유휴 커넥션의 수
..Max. Wait for
..Connection
..1000 ..예외가 발생하여 커넥션을 해제할
..떄까지 최대로 기다리는 시간으로
..1/1000 초 단위
..Validation Query
..select * from tab ..반드시 입력해야 하며 Tomcat
..엔진에서 DB에 접속이 가능한지를
..자체적으로 확인하기 위한 Query

*. Save > Commit Save
*. %Tomcat%\conf\Catalina\localhost\jdbc.xml 파일 열기
*. jdbc.xml 파일에서 <Context> 태그 부분을 찾아서 <ResourceParams> 태그 중 name 속성의 값이 "jdbc/myoracle"인 부분 아래에 보면 이미 작성한 DataSource Properties 가 <parameter> </parameter> 태그 내에 정의 되어 있을 것이다.
*. <ResourceParams>와 </ResourceParams> 태그 사이에 다음 내용을 추가

<parameter>
  <name>removeAbandoned</name>
  <value>true</value>
</parameter>
<parameter>
  <name>removeAbandonedTimeout</name>
  <name>10</value>
</parameter>
  <name>logAbandoned</name>
  <value>true</balue>
</parameter>

* 추가되는 내용의 의미
  Revmoe Abandoned : 사용할 수 있는 커넥션이 부족해진다면 DBCP(Database Connection Pool)는 버려진 커넥션을 찾아 복구하고 재생. 디폴트는 false
  removeAbandonedTimeout : 커넥션이 버려졌다고 간주되기 전에 사용되지 않은 시간(초)를 설정하기 위해 사용. 버러젼 커넥션을 제거하는데 기본적으로 정해진 타임아웃 시가은 300초
  logAbandoned : 만일 커넥션 자원을 낭비한 코드 위치의 로그를 남길 수 있음. 기본은 false

* Tomcat 엔진 Restart



4. Tomcat 엔진에서 올바르게 JDBC 드라이버를 인식하는지 테스트 하기 위한 예제 (JSP)

<%@ page contentType="text/html;charset=euc-kr"
 import = "java.sql.*" %>
 
<%
 Connection con = null;
 Statement stmt = null;
 ResultSet rs = null;
 
 try{
  Class.forName("oracle.jdbc.driver.OracleDriver");
  con = DriverManger.getconnection(
    "jdbc:oracle:thin:@127.0.0.1:1521:ora9",
    "jdbc00", "jdbc00");
  stmt = con.createStatement();
  String query = "select tname from tab";
  rs = stmt.executeQuery(query);
  out.println("<h1>소유한 테이블은 다음과 같습니다.</h1>");
  out.println("<hr><br>");
  while(rs.next()){
   String result = rs.getString(1);
   out.println(result + "<br>");
  }
  rs.close();
  stmt.close();
  con.close();
 } catch(ClassNotFoundException e){
  System.out.println("JDBC 드라이버 로드 실패!");
  out.println("서버 장애가 발생하였습니다.");
 } catch(CSQLException e){
  System.out.println("DB using fail!");
  e.printStackTrace();
  out.println("서버 장애가 발생하였습니다.");
 } finally {
  try{
   if(rs != null) rs.close();
   if(stmt != null) stmt.close();
   if(con != null) con.close();
  }
  catch(SQLException e) { }
 }
%>

5. DataSource를 이용하여 oracle 데이터베이스 계정 내의 테이블 이름 조회하는 예제

oracledatasource.jsp

01  <%@ page contentType="text/html; charset=euc-kr" %>
02  <%@ page import =
03  "javax.naming.*,javax.sql.*,java.sql.*" %>
04  <html>
05   <head>
06    <title>
07     DataSource Test
08    </title>
09   </head>
10   <body>
11    <h3>
12     DataSource 를 이용하여 오라클 데이터베이스의
13     <br>    
14     테이블 이름을 조회하는 test 화면 입니다.
15    </h3>
16    <BR>
17    <hr>
18    <%
19    try{
20     Context initContext = new InitialContext();
21     if(initContext == null )
22     throw new Exception("Boom - No Context");
23     Context envContext  =
24     (Context)initContext.lookup("java:/comp/env");
25     DataSource ds =
26     (DataSource)envContext.lookup("jdbc/myoracle");
27     Connection conn = ds.getConnection();
28     out.println
29     ("DataSource 를 통하여 데이터베이스에 "
30     + "연결하였습니다.<BR>");
31     String queryStr="SELECT * FROM tab";
32     PreparedStatement pstmt =
33     conn.prepareStatement(queryStr);
34     ResultSet rs = pstmt.executeQuery();
35     out.println
36     ("<h5>테이블 조회 결과입니다<BR><BR></h5>");
37     while(rs.next()){
38      System.out.println("rs.next()");
39      out.println(rs.getString(1)+"<BR>");
40     }
41     rs.close();
42     pstmt.close();
43     conn.close();
44    }catch(Exception e) {
45     out.println("<BR>" + e.getMessage());
46     e.printStackTrace();
47    } finally {
try{
if(rs != null) rs.close();
if(ps != null) ps.close();  
if(con != null) con.close();
}catch(Exception e){}    
}
48    %>
49   </body>
50  </html> 

6. login.html

* 웹브라우저에서 사용자가 로그인 정보를 입력할 수 있는 화면
* html의 <form> 태그를 사용하여 id, password 두 가지의 로그인 정볼르 입력받을 수 있도록 구성하여 입력받은 정보를 login.jsp 로 전달
* %Tomcat%\Webapps\jdbc 디렉토리에 저장

login.html

01  <html>
02   <head>
03    <title>
04    회원 로그인
05    </title>
06   </head>
07  
08   <body>
09    <h1> 회원 리스트를 조회하려면
10    로그인 정보를 입력하세요. </h1>
11    <br>
12    <hr>
13    <br>
14    <h3>
15    <form action="/jdbc/login.jsp" method=post>
16     ID&nbsp;&nbsp;&nbsp;
17     <input type=text name=id size=10>
18     <br>
19     암호 <input type=password name=password size=10>
20     <br>
21     <!-- 이름 <input type=text name=name siez=20>
22     <br>-->
23     <input type=submit value=로그인>
24     <input type=reset value=입력취소>
25    </form>
26    </h3>
27    <br>
28    <hr>
29   </body>
30  </html> 

6. login.jsp
* login.html 에서 입력받은 사용자 로그인 정보를 전달받아서 이 정보들을 MemberDAO 객체로 전송
* %Tomcat%\webapps\jdbc 디렉토리에 저장

login.jsp

01  <%@ page contentType="text/html;charset=euc-kr" %>
02  <%@ page import="vo.*,java.util.Vector" %>
03  <jsp:useBean id="member" class="dao.MemberDAO" />
04  <%
05   ListVO memberList = null;
06   String result = "";
07   boolean isEmptyFlag = false;
08  
09   String id = request.getParameter("id");
10   String password = request.getParameter("password"); 
11  
12   switch(member.login(id, password)){
13   case 1:
14    result =
15    "입력하신 비밀 번호가 틀립니다.<br>"
16    + "확인하고 다시 입력하세요<br>";
17    isEmptyFlag = true;
18    break;
19   case 2:
20    result =
21    "회원이 아니시군요.<br>"
22    + "입력하신 id 를 다시 확인하시거나 <br>"
23    + "회원이 아니라면 회원가입을 먼저 하세요.<br>";
24    isEmptyFlag = true;
25    break;
26   default:
27    memberList = member.listMember();
28    if(memberList.getTotal()==0 ||
29    memberList.getList().size()==0){
30     isEmptyFlag=true;
31    }
32   }
33  %>
34  
35  <html>
36   <head>
37   <title>
38   회원 리스트 보기
39   </title>
40   </head>
41  
42   <body>
43   <% if(isEmptyFlag){ 
44   %>
45    <h1>
46    <%=result%>
47    </h1>           
48    <br><br>
49   <% } else {
50   %>
51    <h1> 회원 리스트는 다음과 같습니다.<br></h1>
52    <table border = 3>
53    <tr>
54    <th  align=center><h3>회원 ID</h3></th>
55    <th  align=center><h3>회원 이름</h3></th>
56    </tr>
57   <%       
58    //List 를 포함하기 위한 Vector
59    Vector tempList=memberList.getList();
60    for(int i = 0; i < tempList.size();i++){
61     DetailVO tempVO=(DetailVO)tempList.elementAt(i);
62   %>
63    <tr>
64    <td align=center><h4><%=tempVO.getId()%></h4></td>
65    <td align=center><h4><%=tempVO.getName()%></h4></td>
66    </tr>
67   <%
68    }
69   }
70   %>
71    </table>
72   </body>
73  </html> 

7. DetailVO.java

DetailVO.java

01  package vo;
02  
03  public class DetailVO {
04   /**
05   * 회원 id
06   */
07   private String id;
08  
09   /**
10   * 회원 암호
11   */
12   private String password;
13  
14   /**
15   * 회원 이름
16   */
17   private String name;
18  
19   /**
20   * 기본 Constructor
21   */
22   public DetailVO(){}
23  
24   /**
25   * Constructor
26   * @param  id 조회한 회원 id
27   * @param  password 조회한 회원 password
28   * @param  name 조회한 회원 이름
29   */
30   public DetailVO(String id, String password, String name){
31    this.id = id;
32    this.password = password;
33    this.name = name;
34   }
35  
36   /**
37   * 회원 id Getter Method
38   * @return String 조회한  회원 id
39   */
40   public String getId(){
41    return id;
42   }
43  
44   /**
45   * 회원 id Setter Method
46   * @param String 입력한 회원 id
47   */
48   public void setId(String id){
49    this.id = id;
50   }
51  
52   /**
53   * 회원 id Getter Method
54   * @return String 조회한  회원 password
55   */
56   public String getPassword(){
57    return password;
58   }
59  
60   /**
61   * 회원 id Setter Method
62   * @param String 조회한  회원 password
63   */
64   public void setPassword(String password){
65    this.password = password;
66   }
67  
68   /**
69   * 회원 name Getter Method
70   * @return String 조회한  회원 이름
71   */    
72   public String getName(){
73    return name;
74   }
75  
76   /**
77   * 회원 name Setter Method
78   * @param String 조회한  회원 이름
79   */
80   public void setName(String name){
81    this.name = name;
82   }
83  } 

7. ListVO.java

ListVO.java

01  package vo;
02  
03  import java.util.Vector;
04  
05  public class ListVO {
06   /**
07    * 조회된 회원 리스트
08    */
09   private Vector list;
10  
11   /**
12    * 총 회원 수
13    */
14   private long total;
15   
16   /**
17    * 기본 Constructor
18    */
19   public ListVO(){}
20  
21   /**
22    * 조회된 회원 리스트 Getter Method
23    * @return Vector 조회된 회원 리스트
24    */
25   public Vector getList(){
26       return list;
27   }
28  
29   /**
30    * 조회된 회원 리스트 Setter Method
31    * @param Vector 조회된 회원 리스트
32    */
33   public void setList(Vector list){
34       this.list = list;
35   }
36  
37   /**
38    * 총 회원수 Getter Method
39    * @return long 총 회원수
40    */
41   public long getTotal(){
42       return total; 
43   }
44  
45   /**
46    * 총 회원수 Setter Method
47    * @param long 총 회원수
48    */
49   public void setTotal(long total){
50       this.total = total; 
51   }
52  } 

8. MemberDAO.java

MemberDAO.java
 
01  package dao;
02  
03  import java.util.Vector;
04  import java.sql.*;
05  import javax.naming.*;
06  import javax.sql.*;
07  import vo.*;
08  
09  public class MemberDAO {
10  
11   /**
12   * 총 게시물 갯수를 얻는 Query
13   */
14   private static String stGET_TOTAL_NUM =
15   "SELECT COUNT(*) FROM MEMBER";
16  
17   /**
18   * 게시물 리스트를 얻는 Query
19   */
20   private static String stLIST_MEMBER =
21   "SELECT * FROM MEMBER";
22  
23   /**
24   *  비밀번호 확인 Query
25   */
26   private static String stCHECK_LOGIN =
27   "SELECT PASSWORD FROM MEMBER WHERE ID = ?";
28  
29   /**
30   * DataSource 객체 변수 선언
31   */
32   DataSource ds = null;
33  
34   /**
35   * 기본 Constructor
36   */
37   public MemberDAO()throws Exception {
38    Context initContext = new InitialContext();
39    Context envContext  =
40    (Context)initContext.lookup("java:/comp/env");
41    ds =(DataSource)envContext.lookup("jdbc/myoracle"); 
42   }
43  
44   public ListVO listMember() throws Exception {
45    ListVO retVO = new ListVO();
46    Statement stmt = null;
47    PreparedStatement pstmt = null;
48    ResultSet rs = null;
49    try {
50     Connection conn = ds.getConnection();
51     stmt = conn.createStatement();
52    
53     rs = stmt.executeQuery(stGET_TOTAL_NUM);
54     long total = 0;
55     if(rs.next()){
56      total = rs.getLong(1);
57      retVO.setTotal(total);
58     }
59    
60     pstmt = conn.prepareStatement(stLIST_MEMBER);
61     rs = pstmt.executeQuery();
62     Vector list = new Vector();
63     while(rs.next()){
64      DetailVO tempVO = new DetailVO
65      (rs.getString("id"),
66      rs.getString("password"),
67      rs.getString("name"));
68      list.addElement(tempVO);
69     }
70     retVO.setList(list);
71     rs.close();
72     stmt.close();
73     pstmt.close();
74     conn.close();
75    }catch (Exception e){
76     e.printStackTrace();
77     throw e;
78    }
79    return retVO;
80   }
81  
82   public int login(String id, String inputPass)
83   throws Exception {
84    PreparedStatement pstmt = null;
85    ResultSet rs = null;
86    int result = 0;
87    try {
88     Connection conn = ds.getConnection();
89     pstmt = conn.prepareStatement(stCHECK_LOGIN);
90     pstmt.setString(1,id);
91    
92     rs = pstmt.executeQuery();
93     if(rs.next()){
94      String dbPass = rs.getString(1); 
95      if(dbPass.equals(inputPass)){
96       result = 0;
97      }else {
98       result = 1;
99      }
100     }else {
101      result = 2;
102     } 
103     rs.close();
104     pstmt.close();
105     conn.close();
106    }catch (Exception e){
107     e.printStackTrace(); 
108     throw e;
109    }
110    return result;
111   }
112  } 


2008. 7. 24. 21:59

JDBC 트랜잭션 처리

AutoCommitTest.java

 

01       import java.sql.*;

02      

03       public class AutoCommitTest {

04      

05                  public static void main(String args[]){

06                            Connection con = null;

07                            PreparedStatement ps = null;

08                            int sequence = 0;

09                            String subject = null;

10                            String contents = null;

11                           

12                            try {

13                                       if(args[0] != null

14                                       && args[1] != null

15                                       && args[2] != null){

16                                                  sequence = Integer.parseInt(args[0]);

17                                                  subject = args[1];

18                                                  contents = args[2];

19                                       }

20                            }catch(Exception e){

21                                       System.out.println

22                                       ("데이터베이스 내의 테이블에 존재하는 "

23                                       + "세개의 컬럼에 삽입할 데이터를 입력하세요.");

24                                       return;

25                            }

26                 

27                  try{

28                            String query1 =

29                            " INSERT INTO TRANSACTION1   " +

30                            " (sequence, subject, contents) "+

31                            "  VALUES (?,?,?) ";

32                            String query2 =

33                            " INSERT INTO TRANSACTION2   " +

34                            " (sequence, objects, contents) "+

35                            " VALUES (?,?,?) ";

36                 

37                            Class.forName

38                            ("oracle.jdbc.driver.OracleDriver");

39                            con=DriverManager.getConnection

40                            ("jdbc:oracle:thin:@127.0.0.1:1521:ora9"

41                            ,"jDBC00","jDBC00");

42                            if(con.getAutoCommit()){

43                                       System.out.println

44                                       ("현재의 Connection "

45                                       + "자동 COMMIT 모드입니다.");

46                            }else {

47                                       System.out.println

48                                       ("현재의 Connection "

49                                       + "수동 COMMIT 모드입니다."

50                                       + "SQL  문장을 전송한 후에 "

51                                       + "commit() 이나 rollback() "

52                                       + "메서드를 수행하세요.");

53                            }

54                                                           

55                            ps = con.prepareStatement(query1);

56                            ps.setInt(1,sequence);

57                            ps.setString(2,subject);

58                            ps.setString(3,contents);

59                            ps.executeUpdate();

60                            ps = con.prepareStatement(query2);

61                            ps.setInt(1,sequence);

62                            ps.setString(2,subject);

63                            ps.setString(3,contents);

64                            ps.executeUpdate();

65                            System.out.println

66                            ("두개의 테이블에 데이터 삽입이"

67                            + "완료되었습니다."

68                            + "SQL*PLUS 툴을 이용하여"

69                            + "삽입된 결과를 확인해보세요.");

70                           

71                            ps.close();

72                            con.close();

73                  }catch(Exception e){

74                            System.out.println

75                            ("Exception 발생했습니다."

76                            + " 자세한 내용은 다음과 같습니다.");

77                            System.out.println(e.toString());

78                  }finally {

79                            try{

80                                       if(ps != null) ps.close();                    

81                                       if(con != null) con.close();

82                            }catch(Exception e){}                                

83                  }        

84                  }

85       }

 
위 예제에서는 하나의 테이블에 데이터가 삽입되지 못하더라도 이전에 수행한 테이블의 삽입 문장은 정상적으로 수행되어 결과적으로 하나의 테이블에만 데이터가 삽입되는 결과를 초래함.

왜냐하면 두개의 INSERT 문장이 실행되자 마자 서로 다른 트랜잭션으로 자동 COMMIT 되었기 때문

다음 예제는 두 개의 INSERT 문을 하나의 트랜잭션으로 처리

ExplicitCommitTest.java

 

01       import java.sql.*;

02      

03       public class ExplicitCommitTest {

04      

05                  public static void main(String args[]){

06                            Connection con = null;

07                            PreparedStatement ps = null;

08                            int sequence = 0;

09                            String subject = null;

10                            String contents = null;

11                           

12                            try {

13                                       if(args[0] != null

14                                       && args[1] != null

15                                       && args[2] != null){

16                                                  sequence = Integer.parseInt(args[0]);

17                                                  subject = args[1];

18                                                  contents = args[2];

19                                       }

20                            }catch(Exception e){

21                                       System.out.println

22                                       ("데이터베이스 내의 테이블에 존재하는 "

23                                       + "세개의 컬럼에 삽입할 데이터를 입력하세요.");

24                                       return;

25                            }

26                 

27                  try{

28                            String query1 =

29                            " INSERT INTO TRANSACTION1   " +

30                            " (sequence, subject, contents) "+

31                            "  VALUES (?,?,?) ";

32                            String query2 =

33                            " INSERT INTO TRANSACTION2   " +

34                            " (sequence, objects, contents) "+

35                            " VALUES (?,?,?) ";

36                 

37                            Class.forName

38                            ("oracle.jdbc.driver.OracleDriver");

39                            con=DriverManager.getConnection

40                            ("jdbc:oracle:thin:@127.0.0.1:1521:ora9"

41                            ,"jDBC00","jDBC00");

42                           

43                            con.setAutoCommit(false);

44                            if(con.getAutoCommit()){

45                                       System.out.println

46                                       ("현재의 Connection "

47                                       + "자동 COMMIT 모드입니다.");

48                            }else {

49                                       System.out.println

50                                       ("현재의 Connection "

51                                       + "수동 COMMIT 모드입니다."

52                                       + "SQL  문장을 전송한 후에 "

53                                       + "commit() 이나 rollback() "

54                                       + "메서드를 수행하세요.");

55                            }

56                                                           

57                            ps = con.prepareStatement(query1);

58                            ps.setInt(1,sequence);

59                            ps.setString(2,subject);

60                            ps.setString(3,contents);

61                            ps.executeUpdate();

62                            ps = con.prepareStatement(query2);

63                            ps.setInt(1,sequence);

64                            ps.setString(2,subject);

65                            ps.setString(3,contents);

66                            ps.executeUpdate();

67                           

68                            con.commit();

69                            System.out.println

70                            ("두개의 테이블에 데이터 삽입이"

71                            + "완료되었습니다."

72                            + "SQL*PLUS 툴을 이용하여"

73                            + "삽입된 결과를 확인해보세요.");

74                           

75                            ps.close();

76                            con.close();

77                  }catch(Exception e){

78                            try{

79                                       con.rollback();

80                            }catch(SQLException se){}

81                            System.out.println

82                            ("Exception 발생했습니다.\n"

83                            + "실행된 두개의 INSERT 문장은 "

84                            + "ROLLBACK 처리되었습니다.\n"

85                            + " 자세한 내용은 다음과 같습니다.");

86                            System.out.println(e.toString());

87                           

88                  }finally {

89                            try{

90                                       if(ps != null) ps.close();                    

91                                       if(con != null) con.close();

92                            }catch(Exception e){}                                

93                  }        

94                  }

95       }

 



 

2008. 7. 24. 21:43

JDBC ResultSet의 인터페이스 실습

DataSelect.java

 

01       import java.sql.*;

02      

03       public class DataSelect{

04                 Connection con = null;

05                  Statement  stmt = null;

06                 

07                  public static void main (String args [])  {

08                            DataSelect ds = new DataSelect();

09                            ds.connect();

10                            ds.select();

11                            ds.close();

12                  }

13      

14       public void connect(){

15                  try{

16                            Class.forName("oracle.jdbc.driver.OracleDriver");

17                            con = DriverManager.getConnection

18                            ("jdbc:oracle:thin:@127.0.0.1:1521:ora9",

19                            "jdbc00","jdbc00");

20                            System.out.println("데이터베이스 연결되었습니다.");

21               }catch(ClassNotFoundException e){

22               System.out.println("JDBC Driver load fail!!!");

23               }catch(SQLException e){

24               System.out.println("Connection fail!!!");

25               e.printStackTrace();

26               }

27       }

28        

29        public void close(){

30                 try{

31                            con.close();    

32                            System.out.println("데이터베이스 연결 해제되었습니다.");

33                 }catch(SQLException e){

34                            System.out.println("Connection fail!!!");

35                            e.printStackTrace();

36                 }finally{

37                            try{

38                                        if(con != null) con.close();

39                                       }catch(SQLException e){}

40                 }

41        }

42        

43        public void select(){

44                            try{

45                                       stmt = con.createStatement ();

46                              String query = "select * from emp";

47                              ResultSet rs = stmt.executeQuery(query);

48                              while(rs.next()){

49                                      int id = rs.getInt("id");

50                                      String result = "ID : " + id + "\t";

51                                       String name = "이름 : " + rs.getString(2) + "\t";

52                                      result += name;

53                                      double bonus = rs.getDouble(3);

54                                      result += "BONUS : " + bonus + "\t";

55                                      Date inDate = rs.getDate(4);

56                                      result += "입사일 : " + inDate + "\t";

57                                      String dept = "부서 : " + rs.getString(5) + "\t";

58                                      result += dept;

59                                      System.out.println(result);

60                                                  }                             

61                              System.out.println("emp 테이블의 데이터가 조회되었습니다.");

62                             stmt.close();

63                            }catch(SQLException e){

64                                                  e.printStackTrace();

65                                       }finally {

66                                        try{

67                                         if(stmt != null) stmt.close();

68                                        }catch(SQLException e){}

69                                       }

70        }

71       }

 

 

2008. 7. 24. 21:29

JDBC Statement 인터페이스

1. SQL 전송 메서드

executeUpdate()

데이터베이스에 변경을 가하는 SQL문장을 실행할 때 이용

 

SELECT 문을 제외한 DML DDL문의 전송이 가능하고, 전송 후에는 int 타입으로 변경된 레코드의 수가 리턴되는데, 이 때, DDL문의 경우에는 0이 리턴

executeQuery()

SELECT 문장처럼 데이터를 조회한 결과를 얻으려 할 때 이용

 

ResultSet 반환

Execute()

SQL문의 종류에 상관없이 모든 종류의 SQL문을 실행

 

True 반환 시, ResultSet이 리턴된다는 의미이므로 getResultSet() 메소더를 이용하여 ResultSet을 리턴받음

False 반환 시, 변경된 행의 개수가 리턴된다는 의미이므로 getUpdateCount() 메서드를 이용하여 변경된 행의 개수를 리턴받음

executeBatch()

JDBC 2.0 버전부터 추가

addBatch() 메서드를 이용하여 배치로 처리할 SQL 문장을 묶고, 일괄적으로 데이터베이스로 전송하여 처리하는 메소드임

executeUpdate()를 여러 번 실행하는 것과 유사

 

int 배열을 리턴 배열 내에는 배치처리에 의해 실행된 각각의 SQL 문에 의해 변경된 레코드 수를 저장함

ex) 배치처리할 SQL문이 4개였다면 리턴되는 int 배열의 길이도 4

 

2. Java SQL 타입 비교

SQL Type

Java Type

CHAR

String

VARCHAR

String

LONGVARCHAR

java.io.InputStream

NUMERIC

java.sql.Numeric

DECIMAL

java.sql.Numeric

BIT

Boolean

TINYINT

byte

SMALLINT

short

INTEGER

int

BIGINT

long

REAL

float

FLOAT

float

DOUBLE

double

BINARY

byte[]

LONGBINARY

java.sql.InputStream

DATE

java.sql.Date

TIME

java.sql.Time

TIMESTAMP

java.sql.Timestamp

BLOB

java.sql.Blob

CLOB

java.sql.Clob

 

3. Statement 이용 예제

아래 테이블 생성

id

NUMBER(5)

name

VARCHAR2(25)

bonus

NUMBER(7,2)

In_date

DATE

Dept_name

VARCHAR2(25)

 

01         import java.sql.*;

02        

03         public class TableCreate{

04                      Connection con = null;

05                       Statement  stmt = null;

06                                   

07                       public static void main (String args [])  {

08                                    TableCreate tc = new TableCreate();

09                                    tc.connect();

10                                    tc.createTable();

11                                    tc.close();

12                       }

13        

14                       public void connect(){

15                                    try{

16                                                 Class.forName("oracle.jdbc.driver.OracleDriver");

17                                                 con = DriverManager.getConnection

18                                                 ("jdbc:oracle:thin:@127.0.0.1:1521:ora9",

19                                                 "jdbc00","jdbc00");

20                                                 System.out.println("데이터베이스 연결되었습니다.");

21                               }catch(ClassNotFoundException e){

22                                           System.out.println("JDBC Drvier load fail!!!");

23                          }catch(SQLException e){

24                              System.out.println("Connection fail!!!");

25                              e.printStackTrace();

26                          }

27          }

28          

29          public void close(){

30                      try{

31                                   con.close();      

32                                   System.out.println("데이터베이스 연결 해제되었습니다.");

33                      }catch(SQLException e){

34                                   System.out.println("Connection fail!!!");

35                                   e.printStackTrace();

36                      }finally{

37                                   try{

38                                                  if(con != null) con.close();

39                                                 }catch(SQLException e){}

40                      }

41          }

42          

43          public void createTable(){

44                                   try{

45                                      stmt = con.createStatement ();

46                                      String query = "CREATE  TABLE emp ";

47                                      query += "(id          NUMBER(5) , ";

48                                      query += "name       VARCHAR2(25) , ";

49                                      query += "bonus      NUMBER(7,2) , ";

50                                      query += "in_date    DATE, ";

51                                      query += "dept_name  VARCHAR2(25))" ;

52                                     int rowcount = stmt.executeUpdate(query);

53                                     System.out.println("테이블 생성이 완료되었습니다.");

54                                     stmt.close();

55                                    }catch(SQLException e){

56                                                 e.printStackTrace();

57                                    }finally {

58                                                  try{

59                                                   if(stmt != null) stmt.close();

60                                                  }catch(SQLException e){}

61                                                 }

62          }

63         }

 

4. emp 테이블에 데이터를 삽입하는 예제

 

01         import java.sql.*;

02        

03         public class DataInsert{

04                      Connection con = null;

05                                    Statement  stmt = null;

06                                   

07                                    public static void main (String args [])  {

08                                    DataInsert di = new DataInsert();

09                                    di.connect();

10                                    di.insert();

11                                                 di.close();

12                       }

13        

14                       public void connect(){

15                                    try{

16                                                 Class.forName("oracle.jdbc.driver.OracleDriver");

17                                                 con = DriverManager.getConnection

18                                                 ("jdbc:oracle:thin:@127.0.0.1:1521:ora9",

19                                                 "jdbc00","jdbc00");

20                                                 System.out.println("데이터베이스 연결되었습니다.");

21                      }catch(ClassNotFoundException e){

22                                   System.out.println("JDBC Driver load fail!!!");

23           }catch(SQLException e){

24                                   System.out.println("Connection fail!!!");

25                                   e.printStackTrace();

26           }

27          }

28          

29          public void close(){

30                      try{

31                                   con.close();      

32                                   System.out.println("데이터베이스 연결 해제되었습니다.");

33                      }catch(SQLException e){

34                                   System.out.println("Connection fail!!!");

35                                   e.printStackTrace();

36                      }finally{

37                                   try{

38                                                  if(con != null) con.close();

39                                                 }catch(SQLException e){}

40                      }

41          }

42          

43          public void insert(){

44                                   try{

45                                                              stmt = con.createStatement ();

46                                      String query = "insert into emp values(";

47                                      query += "00001,'길동',50000.00,";

48                                      query += "TO_DATE('2001/01/01', 'YYYY/MM/DD'),'인사부')";

49                                      int rowcount = stmt.executeUpdate(query);

50                                                 query = "insert into emp values(";

51                                      query += "00002,'심청이',75000.00,";

52                                      query += "TO_DATE('2000/01/01', 'YYYY/MM/DD'),'총무부')";

53                                      rowcount += stmt.executeUpdate(query);

54                                      query = "insert into emp values(";

55                                      query += "00003,'대장금',80000.00,";

56                                      query += "TO_DATE('1998/01/01', 'YYYY/MM/DD'),'기획부')";

57                                      rowcount += stmt.executeUpdate(query);

58                                     System.out.println

59                                     ("emp 테이블에" + rowcount + " 개의 데이터가 삽입되었습니다.");

60                                     stmt.close();

61                                    }catch(SQLException e){

62                                                              e.printStackTrace();

63                                                 }finally {

64                                                  try{

65                                                   if(stmt != null) stmt.close();

66                                                  }catch(SQLException e){}

67                                                 }

68          }

69         }

 

5. emp 테이블의 모든 데이터를 조회

 

01         import java.sql.*;

02        

03         public class DataSelect{

04                      Connection con = null;

05                       Statement  stmt = null;

06                                   

07                       public static void main (String args [])  {

08                                    DataSelect ds = new DataSelect();

09                                    ds.connect();

10                                    ds.select();

11                                    ds.close();

12                       }

13        

14                       public void connect(){

15                                    try{

16                                                 Class.forName("oracle.jdbc.driver.OracleDriver");

17                                                 con = DriverManager.getConnection

18                                                 ("jdbc:oracle:thin:@127.0.0.1:1521:ora9",

19                                                 "jdbc00","jdbc00");

20                                                 System.out.println("데이터베이스 연결되었습니다.");

21                      }catch(ClassNotFoundException e){

22                                   System.out.println("JDBC Driver load fail!!!");

23           }catch(SQLException e){

24                                   System.out.println("Connection fail!!!");

25                                   e.printStackTrace();

26           }

27          }

28          

29          public void close(){

30                      try{

31                                   con.close();      

32                                   System.out.println("데이터베이스 연결 해제되었습니다.");

33                      }catch(SQLException e){

34                                   System.out.println("Connection fail!!!");

35                                   e.printStackTrace();

36                      }finally{

37                                   try{

38                                                  if(con != null) con.close();

39                                                 }catch(SQLException e){}

40                      }

41          }

42          

43          public void select(){

44                                   try{

45                                      stmt = con.createStatement ();

46                                      String query = "select * from emp";

47                                      ResultSet rs = stmt.executeQuery(query);

48                                      System.out.println("emp 테이블의 데이터가 조회되었습니다.");

49                                      stmt.close();

50                                    }catch(SQLException e){

51                                                              e.printStackTrace();

52                                                 }finally {

53                                                   try{

54                                                   if(stmt != null) stmt.close();

55                                                  }catch(SQLException e){}

56                                                 }

57          }

58         }

 

6. 실습

 

l       emp 테이블에서 이름이 홍길동이라는 사람의 부서가 인사부에서 정보부로 이동

l       따라서, name홍길동인 데이터의 dept_name 컬럼의 값을 정보부로 수정하는 예제를 작성

l       이어서, ‘대장금이라는 사람이 회사를 퇴사하였다고 가정하고, name대장금인 데이터를 emp 테이블에서 삭제하는 예를 구현

 

01         import java.sql.*;

02        

03         public class DataUpdateDelete{

04                      Connection con = null;

05                       Statement  stmt = null;

06                                   

07                       public static void main (String args [])  {

08                                    DataUpdateDelete dud = new DataUpdateDelete();

09                                    dud.connect();

10                                    dud.updateDelete();

11                                    dud.close();

12                       }

13        

14                       public void connect(){

15                                    try{

16                                                 Class.forName("oracle.jdbc.driver.OracleDriver");

17                                                 con = DriverManager.getConnection

18                                                 ("jdbc:oracle:thin:@127.0.0.1:1521:ora9",

19                                                 "jdbc00","jdbc00");

20                                                 System.out.println("데이터베이스 연결되었습니다.");

21                      }catch(ClassNotFoundException e){

22                                   System.out.println("JDBC Driver load fail!!!");

23           }catch(SQLException e){

24                                   System.out.println("Connection fail!!!");

25                                   e.printStackTrace();

26           }

27          }

28          

29          public void close(){

30                      try{

31                                   con.close();      

32                                   System.out.println("데이터베이스 연결 해제되었습니다.");

33                      }catch(SQLException e){

34                                   System.out.println("Connection fail!!!");

35                                   e.printStackTrace();

36                      }finally{

37                                   try{

38                                                  if(con != null) con.close();

39                                                 }catch(SQLException e){}

40                      }

41          }

42          

43          public void updateDelete(){

44                                    try{

45                                     stmt = con.createStatement ();

46                                     String query = "update emp set dept_name = '정보부' ";

47                                     query  += "where name = '홍길동'";

48                                                 int rowcount = stmt.executeUpdate(query);             

49                                                 System.out.println

50                                                 ("emp 테이블에서 " + rowcount

51                                                 + " 건의 데이터가 수정되었습니다.");

52                                     query = "delete emp where name = '대장금'";

53                                     rowcount = stmt.executeUpdate(query);

54                                     System.out.println

55                                                 ("emp 테이블에서 " + rowcount

56                                                 + " 건의 데이터가 삭제되었습니다.");

57                                                 stmt.close();

58                                                 }catch(SQLException e){

59                                                              e.printStackTrace();

60                                                 }finally {

61                                                              try{

62                                                                            if(stmt != null) stmt.close();

63                                                              }catch(SQLException e){}

64                                                 }

65          }

66         }

 

7. 예제

01         import java.sql.*;

02        

03         public class ExecuteTest{

04                      Connection con = null;

05                       Statement  stmt = null;

06                      

07                       public static void main (String args [])  {

08                                    if(args.length < 1)

09                                    System.out.print

10                                    ("사용법 : java ExecuteTest ");

11                                    System.out.println

12                                    (" 실행할SQL문종류(insert or select)");

13                                    ExecuteTest et = new ExecuteTest();

14                                    et.connect();

15                                    et.test(args[0]);

16                                    et.close();

17                       }

18        

19                       public void connect(){

20                                    try{

21                                                 Class.forName("oracle.jdbc.driver.OracleDriver");

22                                                 con = DriverManager.getConnection

23                                                 ("jdbc:oracle:thin:@127.0.0.1:1521:ora9",

24                                                 "jdbc00","jdbc00");

25                                                 System.out.println("데이터베이스 연결되었습니다.");

26                      }catch(ClassNotFoundException e){

27                                   System.out.println("JDBC Driver load fail!!!");

28                 }catch(SQLException e){

29                                   System.out.println("Connection fail!!!");

30                                   e.printStackTrace();

31                }

32          }

33          

34          public void close(){

35                      try{

36                                   con.close();      

37                                   System.out.println("데이터베이스 연결 해제되었습니다.");

38                      }catch(SQLException e){

39                                   System.out.println("Connection fail!!!");

40                                   e.printStackTrace();

41                      }finally{

42                                   try{

43                                                  if(con != null) con.close();

44                                                 }catch(SQLException e){}

45                      }

46          }

47          

48          public void test(String sql){

49                                    try{

50                                     String query = null;

51                                     int rowcount = 0;

52                                     ResultSet rs = null;

53                                     stmt = con.createStatement ();

54                                if(sql.equals("insert") || sql.equals("INSERT")){

55                                      query = "insert into emp values(";

56                                      query += "00004,'강감찬', 90000.00,";

57                                      query += "TO_DATE('1997/01/01','YYYY/MM/DD'),'기획부')";

58                                    }else if(sql.equals("select") || sql.equals("SELECT")){

59                                                 query = "select * from emp";

60                               }

61                                    boolean flag = stmt.execute(query);

62                       if(flag) {

63                                   rs = stmt.getResultSet();

64                                   System.out.println

65                              ("emp 테이블의 모든 데이터를 조회하였습니다.");

66                              rs.close();

67                        }

68                        else {

69                                    rowcount = stmt.getUpdateCount();

70                                    System.out.print

71                                   ("emp 테이블에" + rowcount );

72                                   System.out.println

73                                   (" 개의 데이터가 삽입되었습니다.");

74                        }

75                        stmt.close();

76                      }catch(SQLException e){

77                                    e.printStackTrace();

78                                    }finally {

79                                     try{

80                                      if(stmt != null) stmt.close();

81                                     }catch(SQLException e){}

82                                    }

83          }

84         }

 

8. 예제

01         import java.sql.*;

02        

03         public class BatchTest{

04                      Connection con = null;

05                       Statement  stmt = null;

06                                   

07                       public static void main (String args [])  {

08                                    BatchTest bt = new BatchTest();

09                                    bt.connect();

10                                    bt.insertBatch();

11                                    bt.close();

12                       }

13        

14                       public void connect(){

15                                    try{

16                                                 Class.forName("oracle.jdbc.driver.OracleDriver");

17                                                 con = DriverManager.getConnection

18                                                 ("jdbc:oracle:thin:@127.0.0.1:1521:ora9",

19                                                 "jdbc00","jdbc00");

20                                                 System.out.println("데이터베이스 연결되었습니다.");

21                                 }catch(ClassNotFoundException e){

22                              System.out.println("JDBC Driver load fail!!!");

23                            }catch(SQLException e){

24                              System.out.println("Connection fail!!!");

25                              e.printStackTrace();

26           }

27          }

 

28          

29          public void close(){

30                      try{

31                                   con.close();      

32                                   System.out.println("데이터베이스 연결 해제되었습니다.");

33                      }catch(SQLException e){

34                                   System.out.println("Connection fail!!!");

35                                   e.printStackTrace();

36                      }finally{

37                                   try{

38                                                  if(con != null) con.close();

39                                                 }catch(SQLException e){}

40                      }

41          }

42          

43          public void insertBatch(){

44                                   try{

45                                     stmt = con.createStatement ();

46                                     String query ="insert into emp values(";

47                                     query += "00005,'김유신',75000.00,";

48                                     query += "TO_DATE('2000/07/01','YYYY/MM/DD'),'인사부')";

49                                     stmt.addBatch(query);

50                                     query = "insert into emp values(";

51                                     query += "00006,'권율', 80000.00,";

52                                     query += "TO_DATE('1998/07/01', 'YYYY/MM/DD'),'기획부')";

53                                     stmt.addBatch(query);

54                                     query = "insert into emp values(";

55                                     query += "00005,'계백', 75000.00,";

56                                     query += "TO_DATE('2001/07/01', 'YYYY/MM/DD'),'총무부')";

57                                     stmt.addBatch(query);

58                                     int [] rowcount = stmt.executeBatch();

59                                     for(int i = 0; i < rowcount.length; i++){

60                                                 System.out.print

61                                            ("배치작업에 의해 " + rowcount[i] );

62                                                 System.out.println

63                                                 (" 개의 데이터가 삽입되었습니다.");

64                                     }                                                              

65                                     stmt.close();

66                                    }catch(SQLException e){

67                                                              e.printStackTrace();

68                                                 }finally {

69                                                  try{

70                                                   if(stmt != null) stmt.close();

71                                                  }catch(SQLException e){}

72                                                 }

73          }

74         }

 

2008. 7. 24. 20:29

JDBC Connection 생성

1. 몇가지 데이터베이스에 접속하기 위한 드라이버 로딩 방법

Driver Name

Example

JDBC-ODBC

Bridge JDK

기본드라이버

Class.forName(“sun.jdbc.odbc.jdbcOdbc Driver”);

Oracle

Class.forName(“oracle.jdbc.driver.Oracle Driver”);

mSQL

Class.forName(“imaginary.sql.iMsql Driver”);

MySQL

Class.forName(“org.git.mm.mysql. Driver”);

SyBase

Class.forName(“com.sybase.jdbc2.jdbc.Syb Driver”);

Informix

Class.forName(“com.informix.jdbc.Ifx Driver”);



2. 해당 데이터 베이스 접속

try {
  // URL, ID, Password
  Connection con = DriverManager.getConnection("jdbc:orcle:thin:@70.12.220.33:1521:ora9", "scott", "tiger");
} catch(SQLException e){
  System.out.println("Connection fail!!!");
}

3. JDBC UL 기술 정보

드라이버 Name

URL

JDBC-ODBC

Bridge

Jdbc:odbc:[;=]

Oracle

OCI URL Type

Jdbc:oracle:oci:<userid>/<password>@<dbname>

Jdbc:oracle:oci:<userid>/<password>@<tns-name-value-pair>

Thin URLType

Jdbc.oracle:thin:<userid>/<password>@<host>:<port>:<dbname>

Jdbc:orcle:thin:<userid>/<password>@<tns-name-value-pair>

mSQL

Jdbc:msql://<hostname>:<port>/<dbname>

MySQL

Jdbc:mysql://<hostname>:<port>/<dbname>

SyBase

Jdbc:Sybase:Tds:<ip>:<port>

Informix

Jdbc:Informix-sqli://<ip>:<port>/<dbname>:INFORMIXSERVER

Postgres

Jdbc:postgresql://<ip>:<port>/<dbname>



4. Connection 인터페이스의 메소드들

# SQL문을 생성하여 전송하거나 PL/SQL 블록을 활용하기 위한 메소드
   : createStatement(), prepareStatement(), prepareCall(),

# 기본 연결 정보를 바탕으로 transaction 처리에 관한 메소드
  : getAutoCommit(), setAutoCommit(), commit(), rollback()
  -> 기본 설정은 setAutoCommit(true) 상태이므로 auto-commit 상태임

# 기본적인 Error나 Warning을 처리하기 위한 메소드
  : claerWarnings(), getWarnings()

# Connection 객체 사용 후 닫기를 위한 메소드
  : close(), isClosed()
  -> 연결을 해제하면서 연결에 사용된 모든 변수나 메모리 자원을 반납하는 과정으로 이 메서드 호출 이전에
      JDBC Program에서 사용했던 ResultSet객체나 Statement 객체의 close() 메서드를 먼저 호출하여
      객체를 가비지 콜렉션한 다음 Connection 객체의 close() 메서드를 호출하여야 함.

5. 예제

Oracle 9i 데이터베이스에 연결

 

01         import java.sql.*;

02        

03         class ConnectionTest{

04                       public static void main(String args[]){

05                      Connection con = null;

06                      try{

07                                   Class.forName("oracle.jdbc.driver.OracleDriver");

08                                   con = DriverManager.getConnection

09                                   ("jdbc:oracle:thin:@127.0.0.1:1521:ora9",

10                                   "jdbc00","jdbc00");

11                                   System.out.println("데이터베이스 연결 성공했습니다.");

12                              con.close();

13                      }catch(ClassNotFoundException e){

14                                   System.out.println("JDBC Drvier load fail!!!");

15                      }catch(SQLException e){

16                                   System.out.println("Connection fail!!!");

17                                   e.printStackTrace();

18                      }

19                      finally{

20                                   try{

21                                                  if(con != null) con.close();

22                                                 }catch(SQLException e){}

23                      }

24          }

25         }          



6. Log4J를 이용한 출력 결과

 

import java.sql.*;

import org.apache.log4j.*;

 

class ConnectionTest_Log{

           /*

           Logger 클래스의 인스턴스를 생성합니다.

           SimpleLog.class 객체가 이미 생성되어 있다면

           생성되어 있는 객체가 반환된다.

           객체가 생성되어 있지 않다면 새로운 객체를 생성한다.

           */

           static Logger logger = Logger.getLogger(ConnectionTest_Log.class);

           public static void main(String args[]) {

                     /*

                     화면 콘솔로 로그 출력을 하기 위한 간단한 설정입니다.

                     %p : 로그 이벤트 레벨을 출력하는 패턴을 설정합니다.

                     [%l%] : 로그 이벤트가 발생한 자바 소스 파일 이름,

                     로그 이벤트가 발생한 소스 라인, 메서드 이름을 출력하는 패턴을 설정.

                     -%m%n : 로그 이벤트 출력 메서드에서 지정한 문자열을

                     출력하는 패턴을 설정합니다.

                     */

                     String pattern = "%p [%l] - %m%n";

                     PatternLayout layout = new PatternLayout(pattern);

                     ConsoleAppender console = new ConsoleAppender(layout);

                     BasicConfigurator.configure(console);

                     Connection con = null;

                     try {

                                Class.forName("oracle.jdbc.driver.OracleDriver");         

                                con = DriverManager.getConnection(

                                          "jdbc:oracle:thin:@127.0.0.1:1521:ora9",

                                          "jdbc00", "jdbc00");

                                /*

                                로그 이벤트 레벨 INFO 로그 레벨로

지정된 문자열 내용을 출력합니다.

                                */

                                logger.info("데이터베이스 연결 성공했습니다.");

                                con.close();

                     } catch(ClassNotFoundException e){

                                /*

                                로그 이벤트 레벨 ERROR 로그 레벨로

                                지정된 문자열 내용을 출력합니다.

                                */

                                logger.error("JDBC Driver load fail!!!");

                     }catch(SQLException e) {

                                /*

                                로그 이벤트 레벨 ERROR 로그 레벨로

                                지정된 문자열 내용을 출력합니다.

                                */

                                logger.error("Connection fail!!!");

                     }

                     finally{

                                try{

                                          if(con != null) con.close();

                                } ctch(SQLException e) { }

                     }

           }

}



오타가 있을수 있음.
2008. 7. 21. 21:28

JDBC 드라이버의 한글 처리

한글 처리 과정

사용자 삽입 이미지


자바 프로그램이 사용하는 인코딩은 유니코드 2.0 이고 데이터베이스는 그 종류에 따라 KSC5601, UTF8, 8859-1 등의 인코딩을 사용. 따라서, JDBC 드라이버는 데이터베이스 전송시 자바 프로그램과 해당 데이터베이스 간의 인코딩을 변환해야 할 필요가 있음.

Oracle 드라이버의 문사셋 환경

사용자 삽입 이미지


데이터베이스 문자셋이 "US77ASCII"나 "WE8ISO8859P1" 일 때와 "KO16KSC5601"일 때 다음과 같이 달라 질 수 있음.

1. 데이터베이스 문자셋이 "US7ASCII"나 WE8ISO8859P1"이라면 JDBC 드라이버가 데이터를 무조건 "UTF16"로 변환시킨 후 이것을 클라이언트측의 JDBC PROGRAM에 전달

2. 데이터베이스의 문자셋이 "KO16KSC5602"이라면, 먼저 데이터를 "UTF8"으로 변환한 후 "UTF16"로 다시 변환해서 데이터를 JDBC 프로그램에 넘겨줌. 이렇게 하기 위해서는 클라이언트의 NLS_LANG 환경변수가 "US7ASCII"나 "WE8ISO8859P1"이 아닌 값으로 설정이 되어야 한다. 그래서, orcal oci 드라이버는 클라이언트의 NLS_LANG을 "KO16KSC5601"이나 "UTF8"로 설정하면 JDBC 드라이버가 데이터를 "UTF8"로 변환한 후에 다시 "UTF16"으로 변환해서 JDBC 프로그램에 데이터를 전달한다.

* Oracle thin 드라이버의 경우에는 클라이언트의 환경과 상관없이 데이터베이스의 문자셋이 "KO16KSC5601"로만 설정되어 있으면 한글을 이용하는 데 큰 문제가 없음. 이럴 경우 JDBC PROGRAM에서 데이터베이스로 한글 데이터 전송시에는 해당 한글을 UTF8로 인코딩하면서 크기가 많이 증가하고 이러한 문자를 받은 Oracle 데이터베이스는 상당히 큰 크기의 문자를 전달받게 된다.

ex) varchar2(10)의 길이로 만들어진 컬럼에 JDBC 프로그램을 통하여 '가나다라마'라는 데이터를 만들어서 JDBC 드라이버를 거쳐서 데이터베이스로 전달하는 경우, 데이터베이스의 varchar2(10)의 길이로 만들어진 컬럼에는 '가나다라마'라는 데이터 크기가 너무 커서 삽입할 수 없다는 오류를 볼 수 있다.

이런 경우 다음과 같이 문자셋을 변환해 넣어주면 정상으로 동장

String name = "가나다라마";
String name_KS = new String(name.getBytes("8859_1"), "KSC5601");


이렇게 문자셋을 설정하여 변경하면 "UTF8"로 변환되는 과정을 막으므로 해당 쿼리가 에러 없이 정상으로 실행된다. 하지만 한글이 1300자 내외를 넘을 경우에는 CLOB이라는 데이터 Type을 사용할 수 있음.
2008. 7. 21. 21:09

JDBC 드라이버의 Type에 따른 분류

사용자 삽입 이미지


드라이버 Type

순수 Java 구현

NETWORK PROTOCOL

TYPE 1 JDBC-ODBC bridge driver

No

(ODBC 드라이버 필요)

Direct

TYPE 2 Native-API partly Java driver

No

(C, C++ 라이브러리 포함)

Direct

TYPE 3 JDBC-NET Protocol All Java Driver

Yes(애플릿 사용 가능)

Connector 요구

(데이터베이스와 미들웨어 서버간)

TYPE 4 Native-protocol pure java driver

Yes(애플릿 사용 가능)

direct



- Keyword
JDBC-ODBC Bridge Driver; Native_API/Partly java driver; Net-protocol/all-java driver; Native-protocol/all-java driver

2008. 7. 18. 15:05

Microsoft APIs and frameworks

*    

[hide]

v  d  e

Microsoft APIs and frameworks

 

 

Graphics

Desktop Window Manager · DirectX · Direct3D · GDI · Windows Presentation Foundation · Windows Color System · Windows Image Acquisition · Windows Imaging Component

 

 

Audio

DirectSound · DirectMusic · DirectX plugin · XACT · Speech API

 

 

Multimedia

DirectShow · DirectX Media Objects · DirectX Video Acceleration · Windows Media · Media Foundation · Image Mastering API

 

 

Web

MSHTML · MSXML · RSS Platform · JScript · VBScript · BHO · XMLHttpRequest · SideBar Gadgets

 

 

Data access

Microsoft Data Access Components · Extensible Storage Engine · ADO.NET · ADO.NET Entity Framework · Sync Framework · Jet Engine

 

 

Networking

Winsock (LSP) · Winsock Kernel · Filtering Platform · Network Driver Interface Specification · Windows Rally · BITS · P2P API

 

 

Communication

Messaging API · Telephony API

 

 

Administration and
management

Win32 console · Windows Script Host · Windows Management Instrumentation · Windows PowerShell · Task Scheduler · Offline Files · Shadow Copy · Windows Installer · Windows Error Reporting · Windows Event Log · Common Log File System

 

 

Component model

COM · COM+ · ActiveX · Distributed Component Object Model · .NET Framework

 

 

Libraries

Microsoft Foundation Class (MFC) · Active Template Library (ATL) · Windows Template Library (WTL)

 

 

Driver development

Windows Driver Model (Broadcast Driver Architecture) · Windows Driver Foundation (KMDF · UMDF)

 

 

Security

Crypto API (CAPICOM) · Windows CardSpace · Data protection API · Security Support Provider Interface

 

 

.NET

.NET Framework · ASP.NET · ADO.NET · Remoting · Windows Presentation Foundation · Windows Workflow Foundation · Windows Communication Foundation · Windows CardSpace · XNA · Silverlight · Task Parallel Library

 

 

Software factories

EFx Factory · Enterprise Library · Composite UI · CCF · CSF

 

 

IPC

MSRPC · Named pipes · Memory-mapped file · DDE · MailSlot

 

 

Accessibility

Active Accessibility · UI Automation

 

 

Text and multilingual
support

Text Services Framework · Text Object Model · Input method editor · Language Interface Pack · Multilingual User Interface · Uniscribe

 

 

Games

Direct3D · D3DX · DirectSound · DirectInput · DirectPlay · DirectMusic · Managed DirectX · Microsoft XNA


Retrieved from "http://en.wikipedia.org/wiki/ActiveX_Data_Objects"