Try구문 괄호에 Autoclosable을 implement한 소캣 객체가 들어갈 경우 try 구문이 끝나면서 알아서 소캣도 닫치는 점을 이용함.
JDK 7버전부터 가능해진 구문임.
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
//Template Method Pattern
public abstract class ConnectAgent3 {
static final String path = "jdbc:oracle:thin:@thinker.ipdisk.co.kr:1521:orcl";
static final String userId = "user00";
static final String userPw = "user00";
public void execute() throws Exception {
try(Connection con2= DriverManager.getConnection(path, userId, userPw);
) {
doJob();
System.out.println(con);
}
}
protected abstract void doJob() throws Exception;
}
------------------------------------------------------------------------------------------------
Connection이 제대로 닫히는지 보여주기 위한 예제
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
//Template Method Pattern
public abstract class ConnectAgent3 {
static final String path = "jdbc:oracle:thin:@thinker.ipdisk.co.kr:1521:orcl";
static final String userId = "user00";
static final String userPw = "user00";
public void execute() throws Exception {
Connection con = null;
try(Connection con2= DriverManager.getConnection(path, userId, userPw);
) {
con = con2;
doJob();
System.out.println(con);
}
System.out.println(con.isClosed());
}
protected abstract void doJob() throws Exception;
}
------------------------------------------------------------------------------------
Test용 Class
package jdbc;
//Template Method Pattern
public class ConnectTest3 implements Runnable {
public void makeConnection() throws Exception {
new ConnectAgent3() {
@Override
protected void doJob() throws Exception {
System.out.println("Doing Job...");
}
}.execute();
}
@Override
public void run() {
try {
makeConnection();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
ConnectTest3 c = new ConnectTest3();
for (int i=0; i<10; i++) {
Thread t = new Thread(c);
t.start();
}
}
}
'코딩 > Oracle' 카테고리의 다른 글
Oracle SQL - 게시판용 table 생성 예제 (1) (0) | 2014.09.13 |
---|---|
Oracle SQL - Toy Data 데이터 만들기 (0) | 2014.09.13 |
JDBC 연결 예제 1 - Template Method Pattern (0) | 2014.09.13 |
Oracle SQL - JDBC 연결 및 쓰레드를 이용한 반복 연결 예제 (0) | 2014.09.13 |
Oracle SQL - table, sequence 생성과 데이터 insert 예제 (0) | 2014.09.13 |