Database connection pool demo : Connection Pool « Apache Common « Java






Database connection pool demo

import org.apache.commons.pool.impl.GenericObjectPool;
import org.apache.commons.dbcp.*;

import java.sql.*;


public class DBCPDemo{

  public static void main(String args[]) throws Exception{

    // create a generic pool
    GenericObjectPool pool = new GenericObjectPool(null);

    // use the connection factory which will wraped by
    // the PoolableConnectionFactory
    DriverManagerConnectionFactory cf =  new DriverManagerConnectionFactory(
                                            "jdbc:jtds:sqlserver://myserver:1433/tandem", 
                                            "user", 
                                            "pass");

    PoolableConnectionFactory pcf =  new PoolableConnectionFactory(cf, pool, null, "SELECT * FROM mysql.db", false, true);

    // register our pool and give it a name
    new PoolingDriver().registerPool("myPool", pool);

    // get a connection and test it
        Connection conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:myPool");

        // now we can use this pool the way we want.
        System.err.println("Are we connected? " + !conn.isClosed());

        System.err.println("Idle Connections: " + pool.getNumIdle() + ", out of " + pool.getNumActive());

  }
}
           
       








DBCPDemo.zip( 1,214 k)

Related examples in the same category

1.Basic DataSource Example
2.Connection Pool Basics