[JSP] DBCP을 이용한 데이터베이스 연결하기
DBCP는 TOMCAT 에서 제공되는 Connection pool 입니다.
[MySQL 연결방법]
tomcat4.1 과 tomcat5.5 에서 테스트 하였습니다.
1. server.xml 설정
context안에 있는 resource 부분이 디비설정입니다.
<Host name="www.dbtool.co.kr" unpackWARs="true" autoDeploy="true">
<Alias>dbtool.co.kr</Alias>
<Context path="" docBase="D:\home\www.dbtool.co.kr" debug="0" reloadable="true" crossContext="true">
<Resource name="jdbc/dbtool" auth="Container" type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/dbtool"
username=""
password=""
maxActive="100"
maxIdle="10"
removeAbandoned="true"
maxWait="5000" />
</Context>
</Host>
* 위와 같이하면 web.xml은 설정할 필요가 없습니다.
2. 테스트 소스(dbcp.jsp)
<%@ page contentType="text/html;charset=euc-kr" %>
<%@ page import="java.sql.*" %>
<%@ page import="javax.sql.*" %>
<%@ page import="javax.naming.*" %>
<%
Connection con = null;
try{
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:comp/env/" + "jdbc/dbtool");
con = ds.getConnection();
out.println(con);
}catch (Exception e) {
out.println(e.toString());
}
%>
3. 실행결과(dbcp.jsp)
org.apache.tomcat.dbcp.dbcp.PoolableConnection@10a1d2d
위에는 테스트용이고 실제 커넥션 부분은 클래스를 만들어 사용하면 됩니다.
예제>
package kr.co.dbtool.db;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class DatabaseConnection
{
protected String dsname = null;
protected Context ctx = null;
protected DataSource ds = null;
protected Connection con = null;
public DatabaseConnection(){
this.dsname = "jdbc/dbtool";
}
public DatabaseConnection(String dsname){
this.dsname = dsname;
}
/**
*기능 : DBCP Pool Connection 정보를 리턴한다
*@return Connection 정보
*/
public Connection getConnection(){
try {
ctx = new InitialContext();
ds = (DataSource)ctx.lookup("java:comp/env/"+dsname);
con = ds.getConnection();
System.out.println(con);
} catch(SQLException e) {
System.out.println(e.toString());
} catch(NamingException ne) {
System.out.println(ne.toString()+" : ctx => " + ctx);
}
return con;
}
}
아래는 관련 댓글들입니다. 댓글수: 0
