JNDI connection java code

Below is sample code if you are looking readymade JNDI connection java code. Before you will have to configure your server with JNDI name. Please read this link if you would like know how to create JNDI name for database connection: How to confirgure JNDI datasource and use it through JNDI connection java code

package com.javahonk;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.InitialContext;
import javax.sql.DataSource;

public class DBConnectionPool {

	private static DBConnectionPool dbConnectionPool = new DBConnectionPool();

	public DBConnectionPool() {
	}

	public static DBConnectionPool getInstance() {
		return dbConnectionPool;
	}

	private static DataSource getDataSource() {

		InitialContext objContext = null;
		DataSource objDataSource = null;

		try {

			if (objDataSource == null) {
				objContext = new javax.naming.InitialContext();
				objDataSource = (DataSource) objContext.lookup("java:comp/env/jdbc/JNDIName");

			}
		} catch (Exception Ex) {

			Ex.printStackTrace();

		}

		return objDataSource;
	}

	public Connection getConnection()  {

		Connection objCon = null;
		DataSource objDataSource = getDataSource();
			try {
			objCon = objDataSource.getConnection();

		} catch (SQLException Ex) {
			Ex.printStackTrace();

		}

		return objCon;

	}

	public void releaseConnection(Connection conn)  {

		if (conn != null) {
			try {
				conn.close();
			} catch (Exception SqlEx) {
				SqlEx.printStackTrace();
			}
		}
	}

	public static Connection getDBConnection() {

		Connection conn = null;

		DBConnectionPool objDBConnectionPool = DBConnectionPool.getInstance();
		try {
			conn = objDBConnectionPool.getConnection();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;

	}

}

Leave a Reply

Your email address will not be published. Required fields are marked *