How to use data source in a web application for tomcat server

1.first create a context.xml file in META-INF folder in the project and add below lines to it.

<context>
<Resource name="datasource name" auth="Container" type="javax.sql.DataSource"
maxActive="15" maxIdle="10" maxwait="100000"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://host:port/dbname"
username="dbusername" password="dbpassword"/>

</context>

or add below lines in context.xml file available in tomcat_home/conf/  folder under .

<Resource name="datasource name" auth="Container" type="javax.sql.DataSource"
maxActive="15" maxIdle="10" maxwait="100000"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://host:port/dbname"
username="dbusername" password="dbpassword" />

2.Now create class with below code

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import org.apache.log4j.Logger;

public class DBConnection { 
    
private static Logger log=Logger.getLogger(DBConnection.class);
  private Connection con=null;
  private PreparedStatement pst=null;
  private ResultSet rs=null;
  public long startTime, endTime, processedTime;    
    
    
public Connection getConnection(String dsn)throws Exception{
   DataSource datasource = null;
         try {  
   InitialContext initContext = new InitialContext();  
datasource=(DataSource)initContext.lookup("java:/comp/env/"+dsn);
   con = datasource.getConnection();
             
    }
    catch(Exception e){
        log.error(e);
        log.error(e.getCause());
        log.error(e.getMessage());
      
    }
    return con;
}
  
}

3.Now to get db connection use

DBConnection db=new DBConnection();
db.getConnection("datasource");

4.similarly we can configure multiple data source in our web application and can access any other data source in our code by just passing data source name to getConnection(“datasource-name”) method.

Advertisements
This entry was posted in Java, Tomcat. Bookmark the permalink.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s