JAVA : Tomcat DataSources

How to create a MySQL DB Connection pool with Tom Cat

Inside META-INF folder create context.xml file and add following lines

<?xml version="1.0" encoding="UTF-8"?>
	<!-- Test datasource -->
	<Resource name="jdbc/test" auth="Container" type="javax.sql.DataSource"
		username="root" password="" driverClassName="com.mysql.jdbc.Driver"
		url="jdbc:mysql://localhost:3306/test" maxActive="2" maxIdle="1" />

Inside WEB-INF folder open web.xml and add following lines (Child of web-app element)

    <description>Factory for java.sql.Connection</description>


private static final String INIT_CONTEXT_LOOKUP = "java:/comp/env";
private static final String ENV_CONTEXT_LOOKUP = "jdbc/test";

public static Connection getConnection() {
		Connection connection = null;
		try {
			Context initContext = new InitialContext();
			Context envContext = (Context) initContext
			DataSource dataSource = (DataSource) envContext
			return dataSource.getConnection();
		} catch (Exception ex) {
			log.error("connection", ex);
		return connection;

Leave a Reply

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

You are commenting using your 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 )

Connecting to %s

%d bloggers like this: