2012년 2월 12일 일요일

[java] DataSource 사용하기

1. Tomcat context.xml 아래 추가하기

<Resource name="jdbc/yjtest"

          auth="Container" type="javax.sql.DataSource"
          driverClassName="oracle.jdbc.driver.OracleDriver"
          url="jdbc:oracle:thin:@localhost:1523:orcl"
          username="yj"
          password="yj" maxActive="100" maxIdle="30" maxWait="100"
          removeAbandoned="true" removeAbandonedTimeout="60" logAbandoned="true"/>


2. ConnectionManager.java


package connection;

import java.sql.Connection;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class ConnectionManager {
public Connection getConnection() throws Exception {
Connection conn = null;
if (initialized == false) {
initialize();
initialized = true;
}
try {
conn=ds.getConnection();
} catch (Exception e) {
System.out.println("Get connection, process exception: "
+ e.getMessage());
e.printStackTrace(System.out);
}
return conn;
}

public void initialize() throws Exception {
try {
Context ctx = new InitialContext();
Context envContext = (Context) ctx.lookup("java:/comp/env");
ds = (DataSource) envContext.lookup("jdbc/yjtest");
} catch (Exception e) {
System.out.println("Naming service exception: " + e.getMessage());
e.printStackTrace(System.out);
}
}

public void releaseConnection(Connection c) throws Exception {
if (c != null)
c.close();
}

public void closeConnection(Connection c) throws Exception {
if (c != null)
c.close();
}

private DataSource ds;

private boolean initialized;
}

댓글 없음:

댓글 쓰기