Database Connection Pooling in Tomcat


1. Open context.xml file, either in <tomcat installation directory>/conf or in META-INF folder of the web application for which you want to enable database connection pooling. If you do not have one in META-INF directory, create one and copy the contents of the context.xml in <tomcat installation directory>/conf.

2. Copy the following and paste with in the <context> element.  I have it for oracle10g database. You can modify it to suit your database. The following configuration takes care of resource leaks when you forget closing connections or result sets or so.

Connection Pooling will not work for databases with out password.

<Resource name=“Jdbc/myDB”

auth=“Container”

type=“javax.sql.DataSource”

driverClassName=“oracle.jdbc.driver.OracleDriver”

url=your database Connection URL

username=database user name

password=database password maxActive=“20” maxIdle=“10”

maxWait=“-1”

removeAbandoned=“true”

removeAbandonedTimeout=“60”/>

3.  Copy the following and paste it in web.xml of your

web application

<resource-ref>

<description>My connection Pooling</description>

<res-ref-name>Jdbc/myDB</res-ref-name>

<res-type>javax.sql.DataSource</res-type>

<res-auth>Container</res-auth>

</resource-ref>

4.  Code some thing like following to get the Connection

public Connection getMyDBConnection() {

Connection connection =null;

try{

Context initCTX = new InitialContext();

Context envCtx = (Context) initCTX.lookup(“Jdbc/myDB “);

DataSource ds = (DataSource)envCtx.lookup(“Jdbc/QCToolDB”);

connection = ds.getConnection();

}catch(Exception e){

e.printStackTrace();

}

return connection;

}

Advertisements

4 thoughts on “Database Connection Pooling in Tomcat

  1. aravind

    This is a great article. i an new to java and database.
    Do we have to look up (context)..everytime i call getCoonection()?

    Reply
    1. Sukumar Vaddi Post author

      You do not want to look up context every time you require a connection. The example code in the blog is just an idea on how to get connection and not how it is implemented in your application.

      Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s