작성자 : shin-gosoo(hchshin@chol.com)
작성일 : 2007.09.30
새창 보기
초보자를 위한 JDBC를 실습 2탄입니다. (톰캣 , My-sql 환경하에서)
이번 강의는 JDBC 프로그래밍의 기본이 되는 CRUD (C : Create, R : Read, U : Update, D : Delete)를 처리하는 방법입니다.
이번 강의를 위해 사전에 설치할 것들
톰캣 설치(5.0.28)
Mysql 설치(5.0.x)
WTP 설치(1.5.3)
JDBC 환경설정 참조
목차
ConnectionHelper 생성
CRUD 예제 설명
실습예제 다운로드
1. ConnectionHelper 생성
예제 (org.javamaster.comm.db.ConnectionHelper.java)
package org.javamaster.comm.db; import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import javax.naming.*; public class ConnectionHelper { public static Connection getConnection() throws Exception { try { Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/myDS"); return ds.getConnection(); } catch (NamingException ne) { ne.printStackTrace(); throw ne; } catch (SQLException se) { se.printStackTrace(); throw se; } } }
커넥션을 쉽게 얻기 위한 Helper 클래스임.
위 예제는 톰캣용임. (다른 WAS 를 이용시는 해당 벤더의 예제를 참고바람)
2. CRUD 예제 설명
List 예제(ex1.jsp)
<%@ page language="java" contentType="text/html; charset=MS949" %> <%@ page import="java.sql.*" %> <%@ page import="java.text.*" %> <%@ page import="java.util.*" %> <%@ page import="org.javamaster.comm.db.*" %> <%! ... private List List() throws Exception { List list = new ArrayList(); Connection con = null; PreparedStatement stmt = null; ResultSet rs = null; try{ con = ConnectionHelper.getConnection(); stmt = con.prepareStatement("select id, title, reg_date from test order by id desc"); rs = stmt.executeQuery(); while(rs.next()){ HashMap row = new HashMap(); row.put("id",rs.getString("id")); row.put("title",rs.getString("title")); row.put("reg_date",rs.getString("reg_date")); list.add(row); } }finally{ if (rs!=null) { try{ rs.close(); } catch(Exception ignored){} } if (stmt!=null) { try{ stmt.close(); } catch(Exception ignored){} } if (con!=null) { try{ con.close(); } catch(Exception ignored){} } } return list; } ... %>
위 예제는 게시판 형식의 리스트를 출력하기 위한 처리방법이다.
물론 완벽한 리스팅을 위해서는 페이징이나 검색등의 기능을 넣어야 겠지만 이 부분은 다음으로 미루겠다.
19라인에서 보면 ConnectionHelper를 통해 Connection Pool로 부터 Connection 객체를 얻어온다.
얻어온 커넥션은 finally에서 처럼 커넥션을 Close (con.close();) 하면 Connection 객체는 Connection Pool 로 반납된다.
23라인의 HashMap 를 통해 한 행의 각각의 열(컬럼) 정보를 넣고, 이를 List 객체에 추가 시킨다.
HashMap 대신 VO(Value Object) 객체를 이용하는게 정석이지만 여기서는 이방법을 이용한다.
30~40 라인처럼 finally 부분에 반드시 모든 리소스를 해제하는 코드를 위치시킨다.
특히 con.close(); 부분을 finally 넣지 않고 try 부분에 넣으면 try 부분에 exception 이 발생했을때 커넥션을 반납을 하지 않아 큰 문제가 발생할 수 있다.
Insert 예제(ex1.jsp)
<%@ page language="java" contentType="text/html; charset=MS949" %> <%@ page import="java.sql.*" %> <%@ page import="java.text.*" %> <%@ page import="java.util.*" %> <%@ page import="org.javamaster.comm.db.*" %> <%! ... private void Insert(String title, String contents) throws Exception { Connection con = null; PreparedStatement stmt = null; try{ con = ConnectionHelper.getConnection(); StringBuffer sql = new StringBuffer(); sql.append("insert into test (id, title, contents, reg_date) \n"); sql.append("values(NULL, ?, ?, now()) "); stmt = con.prepareStatement(sql.toString()); stmt.setString(1,title); stmt.setString(2,contents); stmt.executeUpdate(); }finally{ if (stmt!=null) { try{ stmt.close(); } catch (Exception ignored){} } if (con!=null) { try{ con.close(); } catch (Exception ignored){} } } } ... %>
위 예제는 입력폼에서 제목 및 내용을 받아 입력처리 하는 부분이다.
Update 예제(ex1.jsp)
<%@ page language="java" contentType="text/html; charset=MS949" %> <%@ page import="java.sql.*" %> <%@ page import="java.text.*" %> <%@ page import="java.util.*" %> <%@ page import="org.javamaster.comm.db.*" %> <%! ... private void Update(int id, String title, String contents) throws Exception { Connection con = null; PreparedStatement stmt = null; try{ con = ConnectionHelper.getConnection(); stmt = con.prepareStatement("update test set title=?, contents=? where id=? "); stmt.setString(1,title); stmt.setString(2,contents); stmt.setInt(3,id); stmt.executeUpdate(); }finally{ if (stmt!=null) { try{ stmt.close(); } catch (Exception ignored){} } if (con!=null) { try{ con.close(); } catch (Exception ignored){} } } } ... %>
위 예제는 수정폼에서 제목 및 내용을 받아 수정처리 하는 부분이다.
Delete 예제(ex1.jsp)
<%@ page language="java" contentType="text/html; charset=MS949" %> <%@ page import="java.sql.*" %> <%@ page import="java.text.*" %> <%@ page import="java.util.*" %> <%@ page import="org.javamaster.comm.db.*" %> <%! ... private void Delete(int id) throws Exception { Connection con = null; PreparedStatement stmt = null; try{ con = ConnectionHelper.getConnection(); stmt = con.prepareStatement("delete from test where id=? "); stmt.setInt(1,id); stmt.executeUpdate(); }finally{ if (stmt!=null) { try{ stmt.close(); } catch (Exception ignored){} } if (con!=null) { try{ con.close(); } catch (Exception ignored){} } } } ... %>
위 예제는 삭제처리 하는 부분이다.
View 예제(ex1.jsp)
<%@ page language="java" contentType="text/html; charset=MS949" %> <%@ page import="java.sql.*" %> <%@ page import="java.text.*" %> <%@ page import="java.util.*" %> <%@ page import="org.javamaster.comm.db.*" %> <%! ... private HashMap View(int id) throws Exception { HashMap row = new HashMap(); Connection con = null; PreparedStatement stmt = null; ResultSet rs = null; try{ con = ConnectionHelper.getConnection(); stmt = con.prepareStatement("select id, title, contents, reg_date from test where id=? "); stmt.setInt(1, id); rs = stmt.executeQuery(); if(rs.next()){ row.put("id",rs.getString("id")); row.put("title",rs.getString("title")); row.put("contents",rs.getString("contents")); row.put("reg_date",rs.getString("reg_date")); } }finally{ if (rs!=null) { try{ rs.close(); } catch(Exception ignored){} } if (stmt!=null) { try{ stmt.close(); } catch(Exception ignored){} } if (con!=null) { try{ con.close(); } catch(Exception ignored){} } } return row; } ... %>
위 예제는 게시판의 상세정보를 얻어 오는 부분이다.