DB를 사용할때 가장 속썩이는 부분이 DB connection pool과 Connection, PreparedStatment, ResultSet 이 클래스들 일것이다.

사용을 했으면 반드시 닫아 주어야 시스템에 문제가 생기지 않는다.

일반적으로 select를 사용해보자

public static void main(String args[]) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String tableName = “”;
try {
conn = ConnectionManager.getConnection();
pstmt = conn.prepareStatement(”select * from tab”);
rs = pstmt.executeQuery();
while(rs.next()) {
tableName = String.format(”tname:%s, tabtype:%s”, rs.getString(1), rs.getString(2));
System.out.println(tableName);
}
} catch(Exception e) {
e.printStackTrace();
} finally {
if(rs != null) try { rs.close(); } catch(Exception e) {}
if(pstmt != null) try { pstmt.close(); } catch(Exception e) {}
if(conn != null) try { conn.close(); } catch(Exception e) {}
}
}

상당히 익숙한 코드들이다. 여기서 유의해 볼것은 while이 있는 부분인데 rs에 있는 데이터의 크기도 크기지만, set을 이용해서 코딩하는것 자체가 한마디로 삽질인데, 이것을 dbutils을 사용해서 한번 줄여 보자

먼저 데이터의 구조를 가지고 있는 클래스를 하나 만든다

public static class TabDTO {
private String tname = “”;
private String tabtype = “”;
public String getTabtype() {
return tabtype;
}
public void setTabtype(String tabtype) {
this.tabtype = tabtype;
}
public String getTname() {
return tname;
}
public void setTname(String tname) {
this.tname = tname;
}

}

이것을 사용해서 위에서 연습한 것과 동일한 것을 만들어 보자

public static void main(String args[]) {
Connection conn = null;
int index = 0;
String tableName = “”;
String query = “select * from tab”;
List list = new ArrayList();

try {
conn = ConnectionManager.getConnection();
QueryRunner runner = new QueryRunner();
ResultSetHandler rsh = new BeanListHandler(TabDTO.class); //레코드 여러건
//ResultSetHandler rsh = new BeanHandler(TabDTO.class); //레코드 1건
Vector v = new Vector();
//v.add(index++, “TBLBANK”);
list = (List)runner.query(conn, query, v.toArray(), rsh);
//TabDTO dto = (TabDTO)runner.query(conn, query, v.toArray(), rsh);

Iterator iter = list.iterator();
while(iter.hasNext()) {
TabDTO dto = new TabDTO();
dto = (TabDTO)iter.next();
tableName = String.format(”tname:%s, tabtype:%s”, dto.getTname(), dto.getTabtype());
System.out.println(tableName);
}
} catch(Exception e) {
e.printStackTrace();
} finally {
if(conn != null) try { conn.close(); } catch(Exception e) {}
}
}
어떤가? 더 어려워졌다고 느끼는 분도 있을것이다. 누구나 그러하니까..

중점적으로 볼것은 QueryRunner, ResultSetHandler 이것들은 항상 같이 쓰이고 BeanListHandler는 데이터가 여러건 즉, 리스트 형태일때 사용한다. QueryRunner의 속을 깊이 들여다 보면, query가 여러개 정의되어 있는데 시간이 있으면 한번 들여다 보는것을 권장한다. 그다음에 Vector로 정의된 부분은 dynamic query,즉 PreparedStatement에 사용되는 것을 순서대로 add하여 사용한다. 참고로 query가 ~~where abe=? and def=? 이렇게 되어 있다면 v.add(1, “a”); v.add(2, “b”) 이렇게 되겠다.

조금전에 QueryRunner의 query를 살펴보았다면, query의 역할을 알 것이고 이것은 Object를 리턴함으로 List로 casting하여 사용하게 된다.

글을 처음 쓰는거라 손가락 무지아프다. 다음편에는 insert, update, delete를 알아보자

작성자 : 박남준(criticalbug@gmail.com)

Posted by 나비:D
:
BLOG main image
by 나비:D

공지사항

카테고리

분류 전체보기 (278)
Programming? (0)
---------------------------.. (0)
나비의삽질 (5)
Application (177)
SQL (51)
Web (27)
etc. (14)
Omnia (0)
---------------------------.. (0)

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

달력

«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
Total :
Today : Yesterday :