Need information on creating a connection pool to the database (irrespective of the database) , and how efficient they are? What are the conditions where they can enhance pe
Creating database connection pool using tomcat
1. Tomcat enter resource inside : conf/context.xml
Put the resource entries in context.xml file:
2. create a class which will create the connection pool
public class MyConnectionFactory {
private static String module = "[ QuoteConnectionFactory ]";
private static QuoteConnectionFactory connectionFactory;
protected QuoteConnectionFactory() {
}
/**
*
* @return=>getInstance() is a static method which will return the instance
* of its own class
*/
public static QuoteConnectionFactory getInstance() {
if (connectionFactory == null)
connectionFactory = new QuoteConnectionFactory();
return connectionFactory;
}
/**
*
* @param jndiName
*/
public Connection getConnection(String jndiName) {
System.out.println("jndiName=======" + jndiName);
Connection conn = null;
InitialContext cxt = null;
DataSource dataSource = null;
try {
cxt = new InitialContext();
Context envContext = (Context)cxt.lookup("java:/comp/env");
dataSource = (DataSource)envContext.lookup(jndiName);
} catch (NamingException e) {
} catch (Exception e) {
}
if (dataSource == null) {
try {
conn = dataSource.getConnection();
} catch (Exception e) {
}
System.out.println("connection===================" + conn);
return conn;
}
}
3. edit web.xml file
DB Connection
jdbc/jndiName
javax.sql.DataSource
Container
4. Use in code
Connection con= QuoteConnectionFactory.getInstance(). getConnection("jndiName");