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;
}

[JAVA] 문자열을 이용하여 함수 호출하기



import java.lang.reflect.*;

public class testtest {

/**
* @param args
* @throws NoSuchMethodException
* @throws SecurityException
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/

public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
// TODO Auto-generated method stub
String func_name="";
testtest ttt = new testtest();
for(int i=0; i<3; i++) {
func_name="ppp"+(i+1);
Method method = testtest.class.getDeclaredMethod(func_name);
System.out.println(method.invoke(ttt, new Object[]{}));
}
}

String ppp1(){
System.out.println("ppp1호출");
return "ppp1";
}
String ppp2() {
System.out.println("ppp2호출");
return "ppp2";
}
String ppp3() {
System.out.println("ppp3호출");
return "ppp3";
}
}



참으로 Exception이 많구나..;;