Java DBCP를 이용한 PoolManager 클래스와 이용법 예제
페이지 정보
본문
-------------------------------------------------------------------------------------
DBCP를 이용하여 Connection 객체를 얻어오는 작업이 빈번하기에
빈즈화 시켜봄
특히 매니져 객체가 한번만 만들어질 수 있도록 변수를 static 으로 지정하였슴
-------------------------------------------------------------------------------------
PoolManager.java 의 소스
package pool;
import java.sql.*;
import javax.sql.*;
import javax.naming.*;
public class PoolManager {
private static PoolManager instance = null;
public static PoolManager getInstance() {
if (instance == null) {
instance = new PoolManager();
}
return instance;
}
public Connection getConnection(){
DataSource ds=null;
Connection con=null;
try{
Context ct1=new InitialContext();
Context ct2=(Context)ct1.lookup("java:comp/env");
ds=(DataSource)ct2.lookup("jdbc/zino");
con=ds.getConnection();
}catch(Exception e){
e.printStackTrace();
}
return con;
}
public void freeConnection(Connection con){
if(con!=null){try{con.close();}catch(Exception e){};}
}
public void freeConnection(Connection con,PreparedStatement pstmt){
if(con!=null){try{con.close();}catch(Exception e){};}
if(pstmt!=null){try{pstmt.close();}catch(Exception e){};}
};
public void freeConnection(Connection con,PreparedStatement pstmt,ResultSet rs){
if(con!=null){try{con.close();}catch(Exception e){};}
if(pstmt!=null){try{pstmt.close();}catch(Exception e){};}
if(rs!=null){try{rs.close();}catch(Exception e){};}
};
}
-------------------------------------------------------------------------------------
위의 풀매니져를 사용하게 될 JSP 소스
-------------------------------------------------------------------------------------
<%@ page import="java.sql.*" %>
<%@ page import="pool.PoolManager" %>
<%
PoolManager pool=PoolManager.getInstance(); // new 가 아님에 주의!! (싱글톤 패턴)
Connection con=pool.getConnection();
String sql="select * from test";
PreparedStatement pstmt=con.prepareStatement(sql);
ResultSet rs=null;
rs=pstmt.executeQuery();
rs.next();
out.print(rs.getString("name"));
pool.freeConnection(con,pstmt,rs);
댓글목록
등록된 댓글이 없습니다.