Friday, 8 November 2013

C3PO Connection Pooling

=>We can use C3PO Connection pooling in standalone applications or web based application to connect with database

=>Here i am using mysql db
=>First download c3po related jars or add dependencies for maven
=>Write the code to create connection pooling

pom.xml for maven dependencies:

<dependencies>

  <dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
            
    <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>

  </dependencies>

Program:

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * 
 * @author ramakrishna.v
 *
 */
public class C3POWithMySQLExample {


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

ComboPooledDataSource cpds = new ComboPooledDataSource();
//loads the mysql jdbc driver
try {
cpds.setDriverClass("com.mysql.jdbc.Driver");
} catch (PropertyVetoException e) {
e.printStackTrace();
}             
cpds.setJdbcUrl("jdbc:mysql://localhost:3306/ramakrishna");
cpds.setUser("root");                                  
cpds.setPassword("root");  

Connection con=cpds.getConnection();
//System.out.println(con);

System.out.println("MinPoolSize:::"+cpds.getMinPoolSize());
System.out.println("MaxPoolSize:::"+cpds.getMaxPoolSize());
System.out.println("InitialSize:::"+cpds.getInitialPoolSize());
System.out.println("=================================================");

cpds.setMinPoolSize(5);
cpds.setMaxPoolSize(25);
cpds.setInitialPoolSize(6);
cpds.setAcquireIncrement(5);

System.out.println("MinPoolSize:::"+cpds.getMinPoolSize());
System.out.println("MaxPoolSize:::"+cpds.getMaxPoolSize());
System.out.println("InitialSize:::"+cpds.getInitialPoolSize());

}

}


Output:

MinPoolSize:::3
MaxPoolSize:::15
InitialSize:::3
=================================================
MinPoolSize:::5
MaxPoolSize:::25
InitialSize:::6


No comments:

Post a Comment