18 장 : JDBC DataSource DataSource JDBC 2.0의 javax.sql 패키지에포함되어도입됨 DataSource 인터페이스는데이터베이스커넥션을만들거나사용하는데좀더유연한아키텍처를제공하기위해도입됨 DataSource를이용할경우, 클라이언트코드는한줄도바꾸지않고서도다른데이터베이스에접속할수있도록해줌 즉 DataSource 는커넥션상세사항들을캡슐화 DataSource 인터페이스구현방식에따른클래스타입들 기본적인 DataSource 클래스 javax.sql.datasource 인터페이스를구현함 커넥션풀링기능을갖추고있는 DataSource 클래스 javax.sql.connectionpooldatasource 인터페이스를구현함 분산트랜잭션을지원하는 DataSource 클래스 ( 14 장 ) javax.sql.xadatasource 인터페이스를구현함 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 1/38 Standalone DataSource 사용하기 1 Standalone DataSource 객체사용하기 (Oracle) DriverManager보다는 DataSource사용을권장함 DataSource 사용하여 Connection 객체생성하기 ( datasource/datasourcetestoracle.java)... import oracle.jdbc.pool.oracledatasource; OracleDataSource ds = new OracleDataSource(); ds.seturl("jdbc:oracle:thin:@xtreme.hanbat.ac.kr:1521:xtrm"); ds.setuser("student"); ds.setpassword("xxxx"); // Connect to the local database Connection conn = ds.getconnection(); // Query the employee names Statement stmt = conn.createstatement();... DriverManager Class.forName("jdbc.driver.OracleDriver"); String url = "jdbc:oracle:thin:@xtreme.hanbat.ac.kr:1521:xtrm"; String user = "student"; Stirng password = "xxxx"; Connection conn = DriverManager.getConnection(url, user, password); Statement stmt = conn.createstatement(); 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 2/38
Standalone DataSource 사용하기 2 Standalone DataSource 객체사용하기 (Derby) DriverManager보다는 DataSource사용을권장함 DataSource 사용하여 Connection 객체생성하기 ( datasource/datasourcetestderby.java)... import org.apache.derby.jdbc.embeddeddatasource; EmbeddedDataSource ds = new EmbeddedDataSource(); ds.setdatabasename( d:/derby/databases/wrox4370.db"); // Connect to the local database Connection conn = ds.getconnection(); // Query the employee names Statement stmt = conn.createstatement();... DriverManager Class.forName("org.apache.derby.jdbc.EmbeddedDriver"); String url = "jdbc:derby:d:/derby/databases/wrox4370.db"; Connection conn = DriverManager.getConnection(url); Statement stmt = conn.createstatement(); 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 3/38 Client/Server DataSource 객체의작동방식 context.bind( MusicStore, oracledatasource) DataSource ds = (DataSource) context.lookup( MusicStore ) LDAP Server Client Connection conn = ds.getconnection(); Oracle DBMS 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 4/38
Client/Server DataSource 사용하기 ( 서버측 ) 준비사항 DataSource 객체를생성해서디렉토리에바인딩해야함 이런일들은대개데이터베이스관리자가하게됨 Hashtable<String,String> env = new Hashtable<String,String>(); env.put( Context.INITIAL_CONTEXT_FACTORY, com.sun.jndi.fscontext.reffscontextfactory ); env.put( Context.PROVIDER_URL, file:/d:/java/jndi/derby ); Context ctx = new InitialContext(env); EmbeddedDataSource ds = new EmbeddedDataSource(); ds.setdatabasename( d:/derby/databases/wrox4370.db ); ctx.rebind( jdbc/musicstore, ds); ( 클라이언트측 ) 사용방법 Hashtable<String,String> env = new Hashtable<String,String>(); env.put( Context.INITIAL_CONTEXT_FACTORY, com.sun.jndi.fscontext.reffscontextfactory ); env.put( Context.PROVIDER_URL, file:/d:/java/jndi/derby ); Context ctx = new InitialContext(env); DataSource ds = (DataSource) ctx.lookup( jdbc/musicstore ); Connection connection = ds.getconnection(); 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 5/38 디렉토리 (Directory) 디렉토리개요 DataSource는대개컨텍스트 (context) 안에서룩업 (lookup) 을실행해서얻어내는경우가많음 컨텍스트는이름과자원을결합시킨다는뜻임 컨텍스트예 : 디렉토리 LDAP (Lightweight Directory Access Protocol) Active Directory X.500 File System ( 서버관점 ) DataSource 객체를생성한다음, 그객체를디렉토리에바인드 (bind) 함 바인드한다는것 (binding) 은디렉토리에게특정한이름을특정한자원과결합하라고명령하는행동임 전화디렉토리 ( 전화번호부 ): 어떤사람의주소와전화번호에대한정보를그사람의이름과바인드함 파일시스템 : Store01.java라는파일을생성하는경우, 파일내용에해당하는수많은바이트들을하드디스크에기록한다음, Store01.java라는이름과바인드하는것임 JDBC가 DBMS 중립적인인터페이스를제공하듯이 JNDI(Java Naming and Directory Interface) 는디렉토리서버중립적인인터페이스를제공함 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 6/38
실습해보기 DataSource 를사용하기위해셋팅하기 필요한라이브러리 JDKv1.4 이상 JNDI 와아래와같은 4 개의서비스제공자를기본적으로포함하고있음 ( 즉 jndi1_2_1.zip 를설치할필요가없음 ) LDAP Server Provider COS Naming Service Provider RMI Registry Service Provider DNS Service Provider JDKv1.3 JNDI 와아래와같은 3 개의서비스제공자를기본적으로포함하고있음 ( 즉 jndi1_2_1.zip 를설치할필요가없음 ) LDAP Server Provider COS Naming Service Provider RMI Registry Service Provider JDKv1.2 JNDI 와아래와같은 1 개의서비스제공자를기본적으로포함하고있음 ( 즉 jndi1_2_1.zip 를설치할필요가없음 ) COS Naming Service Provider ( 사용할경우 ) 필요한라이브러리 File System Service Provider (fscontext1_2beta3.zip)» Lib 폴더밑의 fscontext.jar, providerutil.jar 를 c:\java\lib 로복사한다. 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 7/38 실습해보기 FileSystem-Oracle 용 DataSource 만들기 DataSource 객체를저장 / 사용하기위한디렉토리서버 File System (JNDI File System Service Provider) DBMS Oracle 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 8/38
실습해보기 FileSystem-Oracle 용서버측프로퍼티파일 DataSource-FileSystem-Oracle.properties 871 page # DataSource-FileSystem-Oracle.properties # Oracle # drvname = "oracle.jdbc.driver.oracledriver" # srcurl = "jdbc:oracle:thin:@xtreme.hanbat.ac.kr:1521:xtrm" datasource.factory=com.sun.jndi.fscontext.reffscontextfactory datasource.url=file:/d:/java/jndi/oracle datasource.bindname=jdbc/musicstore datasource.username=student 자신의오라클계정이름 datasource.password=xxxxxx 자신의오라클패스워드 datasource.server=xtreme.hanbat.ac.kr datasource.port=1521 datasource.drivertype=thin datasource.netprotocol=tcp datasource.databasename=xtrm 준비작업 d:\java\jndi\oracle 디렉토리를생성함 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 9/38 실습해보기 FileSystem-Oracle 용 DataSourceServer 1 DataSourceFileSystemOracle.java (1/2) 874-875 page package datasource; import java.sql.*; import javax.sql.*; import javax.naming.*; import java.util.*; import oracle.jdbc.pool.oracledatasource; public class DataSourceFileSystemOracle { static ResourceBundle bundle = ResourceBundle.getBundle( datasource.datasource-filesystem-oracle ); public static void main(string[] args) { try { // create and store parameters which are used to create the context Hashtable<String,String> env = new Hashtable<String,String>(); env.put(context.initial_context_factory, bundle.getstring("datasource.factory")); env.put(context.provider_url, bundle.getstring("datasource.url")); // create the context Context context = new InitialContext(env); 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 10/38
실습해보기 FileSystem-Oracle 용 DataSourceServer 2 DataSourceFileServerOracle.java (2/2) // Create a DataSource object OracleDataSource datasource = new OracleDataSource(); // set the connection parameters String s; s = bundle.getstring("datasource.username"); datasource.setuser(s); s = bundle.getstring("datasource.password"); datasource.setpassword(s); s = bundle.getstring("datasource.drivertype"); datasource.setdrivertype(s); s = bundle.getstring("datasource.netprotocol"); datasource.setnetworkprotocol(s); s = bundle.getstring("datasource.server"); datasource.setservername(s); s = bundle.getstring("datasource.databasename"); datasource.setdatabasename(s); datasource.setportnumber(getport()); String bindname = bundle.getstring("datasource.bindname"); context.rebind(bindname, datasource); System.out.println("DataSource completed"); catch (Exception e) { e.printstacktrace(); static int getport() throws NumberFormatException { String s = bundle.getstring("datasource.port"); return Integer.parseInt(s); 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 11/38 실습해보기 FileSystem-Oracle 용 DataSourceServer 3 DataSourceFileSystemOracle.java 컴파일하기 d:> cd d:\begjavadb\ch18 d:> javac datasource/datasourcefilesystemoracle.java DataSourceFileSytemOracle 실행하기 d:> cd d:\begjavadb\ch18 d:> java datasource.datasourcefilesystemoracle d:\java\jndi\oracle 폴더밑에만들어진.bindings 파일을 notepad로열어내용확인 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 12/38
실습해보기 클라이언트측프로퍼티파일 MusicStore-FileSystem-Oracle.properties 879 page # MusicStore-FileSystem-Oracle.properties datasource.factory=com.sun.jndi.fscontext.reffscontextfactory datasource.url=file:/d:/java/jndi/oracle datasource.bindname=jdbc/musicstore 준비작업 d:\begjavadb\ch18\datasource 에서아래명령을수행함 copy MusicStore-FileSystem-oracle.properties MusicStore.properties 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 13/38 실습해보기 DataSourceClient DataSourceClient.java ( 교재에있는소스를다음과같이수정하는것이필요함 ) 878 page package datasource; import java.sql.*; import javax.sql.*; import javax.naming.*; import java.util.*; public class DataSourceClient { private static ResourceBundle bundle = ResourceBundle.getBundle( datasource.musicstore ); private DataSource datasource; public DataSourceClient() { Context context; try { Hashtable<String,String> env = new Hashtable<String,String>(); env.put(context.initial_context_factory, bundle.getstring("datasource.factory")); env.put(context.provider_url, bundle.getstring("datasource.url")); context = new InitialContext(env); String bindname = bundle.getstring("datasource.bindname"); datasource = (DataSource) context.lookup(bindname); catch (Exception e) { e.printstacktrace(); public Connection getconnection() throws SQLException { return datasource.getconnection(); 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 14/38
실습해보기 DataSourceClient 컴파일하기 DataSourceClient.java 컴파일하기 앞의소스파일을 d:\begjavadb\ch18\datasource\datasourceclient.java 파일로저장 d:> cd d:\begjavadb\ch18 d:> javac datasource/datasourceclient.java DataSourceClient 실행하기 d:> cd d:\begjavadb\ch18 d:> java datasource.datasourceclient 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 15/38 실습해보기 Store 클래스와함께 DataSource 이용하기 connections/storeds.java 881-884 pages... import datasource.*;... DataSourceClient ds = new DataSourceClient(); Connection conn = ds.getconnection();... connections/storeds.java 컴파일하기 소스파일을 d:\begjavadb\ch18\connections\storeds.java 파일로저장 d:> cd d:\begjavadb\ch18 d:> javac connections/storeds.java 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 16/38
실습해보기 TestStoreDS 1 connections/teststoreds.java 884 page package connections; public class TestStoreDS { public static void main(string[] args) { String id = "4"; StoreDS store = new StoreDS(); boolean result = store.findbyprimarykey(id); if (result) { System.out.println("Store retrieved"); System.out.println("Store details: n" + store.tostring()); else { System.out.println("Store NOT retrieved"); 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 17/38 실습해보기 TestStoreDS 2 connections/teststoreds.java 컴파일하기한후실행하기 소스파일을 d:\begjavadb\ch18\connections\teststoreds.java 파일로저장 d:> cd d:\begjavadb\ch18 d:> javac connections/teststoreds.java d:> java connections.teststoreds 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 18/38
FileSystem-Derby 에맞도록변경하기 DataSource 객체를저장 / 사용하기위한디렉토리서버 File System (JNDI File System Service Provider) DBMS Derby 서버측 ( 변경필요 ) DataSource-FileSystem-Derby.properties ( 새로작성 ) DataSourceFileServerDerby.java ( 새로작성 ) 클라이언트측 ( 변경불필요 ) MustsicStore-FileSystem-Derby.properties MusicStore.properties DataSourceClient.java ( 무변경 ) StoreDS.java ( 무변경 ) TestStoreDS.java ( 무변경 ) 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 19/38 DataSourceFileServerDerby datasource/datasourcefileserverderby.java 887-889 pages package datasource; import java.sql.*; import javax.sql.*; import javax.naming.*; import java.util.*; import org.apache.derby.jdbc.embeddeddatasource; public class DataSourceFileSystemDerby { static ResourceBundle bundle = ResourceBundle.getBundle( datasource.datasource-filesystem-derby ); static String s; public static void main(string[] args) { try { //create and store parameters which are used to create the context Hashtable<String,String> env = new Hashtable<String,String>(); env.put(context.initial_context_factory, bundle.getstring("datasource.factory")); env.put(context.provider_url, bundle.getstring("datasource.url")); //create the context Context context = new InitialContext(env); EmbeddedDataSource csdatasource = new EmbeddedDataSource(); s = bundle.getstring("datasource.databasename"); csdatasource.setdatabasename(s); String bindname = bundle.getstring("datasource.bindname"); context.rebind(bindname, csdatasource); System.out.println("DataSource completed"); catch (Exception e) { e.printstacktrace(); 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 20/38
실습해보기 FileSystem-Derby 실습하기 datasource/datasourcefilesystemderby.java 컴파일하고실행하기 소스파일을 d:\begjavadb\ch18\datasource에저장 d:> cd d:\begjavadb\ch18 d:> javac datasource/datasourcefileserverderby.java d:> java datasource.datasourcefileserverderby ( d:\java\jndi\derby\.bindings 이변경됨 ) connections/teststoreds.java 실행하기 ( 전혀수정없이 ) d:> cd d:\begjavadb\ch18 d:> java connections.teststoreds 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 21/38 File System 대신 LDAP 서버를사용하도록변경하기 DataSource 객체를저장 / 사용하기위한디렉토리서버 Fedora Directory Server (JNDI LDAP Service Provider) DBMS Oracle 서버측 ( 변경필요 ) DataSource-LDAP-Oracle.properties ( 새로작성 ) DataSourceLDAPServerOracle.java ( 새로작성 ) 클라이언트측 ( 변경불필요 ) MusicStore-LDAP-Oracle.properties MusicStore.properties DataSourceClient.java ( 무변경 ) StoreDS.java ( 무변경 ) TestStoreDS.java ( 무변경 ) 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 22/38
변경 1 : DataSource-LDAP-Oracle.properties DataSource-LDAP-Oracle.properties 887 page # DataSource-LDAP-Oracle.properties # Oracle # clsname = "oracle.jdbc.driver.oracledriver" # url = "jdbc:oracle:thin:@xtreme.hanbat.ac.kr:1521:xtrm" datasource.factory=com.sun.jndi.ldap.ldapctxfactory datasource.url=ldap://embedded.hanbat.ac.kr/dc=hanbat,dc=ac,dc=kr datasource.bindname=cn=oracle_musicstore,ou=datasources datasource.username=student 자신의오라클계정이름 datasource.password=xxxxxx 자신의오라클패스워드 datasource.server=xtreme.hanbat.ac.kr datasource.port=1521 datasource.drivertype=thin datasource.netprotocol=tcp datasource.databasename=xtrm 준비작업 embedded.hanbat.ac.kr 에 FDS 서버실행 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 23/38 변경 2 : DataSourceLDAPServerOracle 클래스구현하기 1 DataSourceLDAPServerOracle.java (1/3) package datasource; import java.util.*; import java.sql.*; import javax.sql.*; import javax.naming.*; import javax.naming.directory.*; import oracle.jdbc.pool.oracledatasource; public class DataSourceLDAPServerOracle { final static String rootdn = "cn=directory Manager"; final static String rootpass = "xxxx"; // DataSource Parameter final static ResourceBundle bundle = ResourceBundle.getBundle( datasource.datasource"); public static void main( String[] args ) { // set up environment to access the server Hashtable<String,String> env = new Hashtable<String,String>(); env.put( Context.INITIAL_CONTEXT_FACTORY, bundle.getstring("datasource.factory")); env.put( Context.PROVIDER_URL, bundle.getstring("datasource.url")); env.put( Context.SECURITY_PRINCIPAL, rootdn ); env.put( Context.SECURITY_CREDENTIALS, rootpass ); 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 24/38
변경 2 : DataSourceLDAPServerOracle 클래스구현하기 2 DataSourceLDAPServerOracle.java (2/3) try { // obtain initial directory context using the environment DirContext ctx = new InitialDirContext( env ); // create a DataSource object to add to the directory OracleDataSource datasource = new OracleDataSource(); // set the connection parameters String s; s = bundle.getstring("datasource.username"); datasource.setuser(s); s = bundle.getstring("datasource.password"); datasource.setpassword(s); s = bundle.getstring("datasource.drivertype"); datasource.setdrivertype(s); s = bundle.getstring("datasource.netprotocol"); datasource.setnetworkprotocol(s); s = bundle.getstring("datasource.server"); datasource.setservername(s); s = bundle.getstring("datasource.databasename"); datasource.setdatabasename(s); datasource.setportnumber(getport()); 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 25/38 변경 2 : DataSourceLDAPServerOracle 클래스구현하기 3 DataSourceLDAPServerOracle.java (3/3) // get the name String bindname = bundle.getstring("datasource.bindname"); // bind the DataSource with the name ctx.rebind( bindname, datasource ); System.out.println("DataSource completed"); catch ( NameAlreadyBoundException nabe ) { System.err.println( "value has already been bound!" ); catch ( Exception e ) { System.err.println( e ); static int getport() throws NumberFormatException { String s = bundle.getstring("datasource.port"); return Integer.parseInt(s); 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 26/38
변경 3 : MusicStore-LDAP-oracle.properties MusicStore-LDAP-Oracle.properties # MusicStore-LDAP-Oracle.properties datasource.factory=com.sun.jndi.ldap.ldapctxfactory datasource.url=ldap://embedded.hanbat.ac.kr/dc=hanbat,dc=ac,dc=kr datasource.bindname=cn=oracle_musicstore,ou=datasources 준비작업 d:\begjavadb\ch18> copy MusicStore-LDAP-oracle.properties MusicStore.properties 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 27/38 실습해보기 TestStoreDS connections/teststoreds.java 실행하기 d:> cd d:\begjavadb\ch18 d:> java connections.teststoreds 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 28/38
Connection Pooling : Profiler.java profiler/profiler.java 891 page package profiler; import static java.lang.system.out; public class Profiler { private long m_starttime; private long m_stoptime; private String m_routinename; public void Start(String routinename) { m_starttime = System.currentTimeMillis(); m_routinename = routinename; public void Stop() { m_stoptime = System.currentTimeMillis(); out.printf( Routine [%s] took %d msecs to execute. n, m_routinename, (m_stoptime - m_starttime) ); 컴파일하기 C:\BegJavaDB\Ch18> javac profiler\profiler.java 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 29/38 Connection Pooling : ProfilerTest.java profiler/profilertest.java 893 page package profiler; import static java.lang.system.out; public class ProfilerTest { public static void main(string args[]) { Profiler p = new Profiler(); // Start the profiler p.start("a routine"); for (long ncounter = 0; ncounter < 100; ncounter++) { out.printf( %2d n, ncounter); p.stop(); 컴파일및실행하기 d:\begjavadb\ch18> javac profiler\profilertest.java d:\begjavadb\ch18> java profiler.profilertest 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 30/38
Connection Pooling : DataSourceConnectionPool.java pooling/datasourceconnectionpool.java (1/3) 894-895 pages package pooling; import java.sql.*; import java.util.*; import datasource.*; public class DataSourceConnectionPool { private Vector connections; private String url, username, password; private boolean inuse[]; final private int poolsize = 10; private DataSourceClient client; public DataSourceConnectionPool() throws SQLException { connections = new Vector(poolsize); inuse = new boolean[poolsize]; try { SetupConnectionsPool(); catch (Exception e) { e.printstacktrace(); 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 31/38 Connection Pooling : DataSourceConnectionPool.java 2 pooling/datasourceconnectionpool.java (2/3) 894-895 pages private void SetupConnectionsPool() throws SQLException { for (int i = 0; i < poolsize; i++) { Connection conn = new DataSourceClient().getConnection(); connections.addelement(conn); inuse[i] = false; public void freeconnection(int connectionidx) { inuse[connectionidx] = false; public Connection getconnection() { Connection c = null; for (int idx = 0; idx < connections.size(); idx++) { if (inuse[idx] == false) { c = (Connection) connections.elementat(idx); inuse[idx] = true; return c; 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 32/38
Connection Pooling : DataSourceConnectionPool.java 3 pooling/datasourceconnectionpool.java (3/3) 894-895 pages public void dumpconnectionstatus() { System.out.println(" nconnection Pool Status"); System.out.println(" npool Size is " + connections.size()); for (int i = 0; i < connections.size(); i++) { System.out.println("Pool Index [" + i + "] In Use status = " + inuse[i]); 컴파일하기 d:\begjavadb\ch18> set CLASSPATH=.;d:\java\lib\fscontext.jar;d:\java\lib\providerutil.jar d:\begjavadb\ch18> javac pooling\datasourceconnectionpool.java 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 33/38 Connection Pooling : NonPoolTest.java pooling/nonpooltest.java package pooling; import java.sql.*; import profiler.profiler; import datasource.datasourceclient; public class NonPoolTest { private static ConnectionPool pool; public static void main(string args[]) { Profiler p = new Profiler(); try { Connection c[] = new Connection[10]; p.start("main() in NON PoolTest"); for (int i = 0; i < 10; i++) { c[i] = new DataSourceClient().getConnection(); p.stop(); catch (Exception e) { e.printstacktrace(); 컴파일하기 d:\begjavadb\ch18> javac pooling\nonpooltest.java d:\begjavadb\ch18> java pooling.nonpooltest 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 34/38
Connection Pooling : DataSourcePoolTest.java pooling/datasourcepooltest.java 899-900 pages package pooling; import java.sql.*; import profiler.profiler; public class DataSourcePoolTest { private static DataSourceConnectionPool pool; private static String url = "jdbc:cloudscape:c:/begjavadb/wrox4370.db"; private static String username = ""; private static String password = ""; public static void main(string args[]) { Profiler p = new Profiler(); try { System.out.println("Establish a connection [" + url + "]"); p.start("creating a pool of 10 connections"); pool = new DataSourceConnectionPool(); Connection c[] = new Connection[10]; p.stop(); p.start("main() in PoolTest"); for (int i = 0; i < 10; i++) { c[i] = pool.getconnection(); p.stop(); catch (Exception e) { e.printstacktrace(); 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 35/38 Connection Pooling : DataSourcePoolTest.java 실행하기 실행하기 d:\begjavadb\ch18> javac pooling\datasourcepooltest.java d:\begjavadb\ch18> java pooling.datasourcepooltest 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 36/38
Connection Pooling : 기업형환경에서사용하기 Enterprise JavaBean 에서벤더가제공하는커넥션풀링사용예 import java.sql.*; import javax.sql.*; import javax.naming.*; import java.util.*; public MyEJB ejbcreate() { ConnectionPoolDataSource ds; PooledConnection pc; try { // create and store parameters which are used to create the context context = new InitialContext(env); ds = (ConnectionPoolDataSource) context.lookup(bindname); pc = ds.getpooledconnection(); conn = pc.getconnection(); // // 데이타베이스조작하는코드 // conn.close(); catch (Exception e) { e.printstacktrace(); 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 37/38 Connection Pooling : Oracle 의 ConnectionPool 사용 datasource/connectionpooldatasourceldapserver.java datasource/connectionpooldatasourceclient.java 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 38/38