Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Answers Viewqa JDBC connection pooling

Have Programming Question? Ask it here!
 
 
 


Pushpendra
connection pooling
1 Answer(s)      5 years and a month ago
Posted in : JDBC



Advertisement
View Answers

July 30, 2009 at 3:59 PM


Hi friend,

A connection pool is a cache of database connections maintained by the database.
This results connections can be reused when the database receives future requests for data.
It is used to increase the performance of executing commands on a database.
It open and maintain a database connection for each user.

In JDBC connection pool, a pool of Connection objects is created at the time the application server (or some other server) starts.
These objects are then managed by a pool manager.When the connection pool server starts, it creates a predetermined
number of Connection objects.A client application would then perform a JNDI lookup to retrieve a reference to a
DataSource object that implements the ConnectionPoolDataSource interface. The ConnectionPoolDataSource would return a
Connection object that implemented the PooledConnection interface.

For example :

import java.sql.*;
import java.util.Properties;
import org.apache.commons.dbcp.*;
import org.apache.commons.pool.impl.*;
import org.apache.commons.pool.KeyedObjectPoolFactory;


public class JConPool {

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

GenericObjectPool gObjPool = new GenericObjectPool();

Properties pros = new Properties();
pros.setProperty("Username", "root");
pros.setProperty("Password", "");
ConnectionFactory cf = new DriverConnectionFactory(new com.mysql.jdbc.Driver(),"jdbc:mysql://localhost/commons",pros);


KeyedObjectPoolFactory kopf =new GenericKeyedObjectPoolFactory(null, 8);

PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf,gObjPool,kopf, null, false, true);


for(int i = 0; i < 5; i++) {
gObjPool.addObject();
}


PoolingDriver poold = new PoolingDriver();
poold.registerPool("example", gObjPool);

for(int i = 0; i < 5; i++) {
gObjPool.addObject();
}

Connection connection = java.sql.DriverManager.getConnection("jdbc:apache:commons:dbcp:example");

System.err.println("Connection: " + connection );
PreparedStatement ps = connection.prepareStatement("Select * from tablename where id = ?");

System.err.println("Active: " + gObjPool.getNumActive() + ", Idle: " + gObjPool.getNumIdle());

connection.close();

System.err.println("Active: " + gObjPool.getNumActive() + ", Idle: " + gObjPool.getNumIdle());

}
}

Thanks


Related Tutorials/Questions & Answers:
Advertisements
 

 

 

DMCA.com