//Java program for DB2 connection using JNDI name.
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
/*
* *@Rakesh K
*
*/
public class DB2Connect
{
public static Logger log=Logger.getLogger(DB2Connect.class);
public static Connection getConnection(String dataSourceName) //here dataSourceName is JNDI name
{
log.info("Enter [DB2Connect]getConnection()");
log.info("Data Source Name is: "+dataSourceName);
Connection dbConnection=null;
try{
InitialContext ctx = new InitialContext();
Object objRef = ctx.lookup(dataSourceName);
DataSource dataSource = (DataSource)objRef;
dbConnection = dataSource.getConnection();
}catch(SQLException ex){
log.error("Exceptio found at [DB2Connect]getConnection():"+ex);
}catch(NamingException ex){
log.error("Exceptio found at [DB2Connect]getConnection():"+ex);
}catch(Exception ex){
log.error("Exceptio found at [DB2Connect]getConnection():"+ex);
}
return dbConnection;
}
public static void closeConnection(Connection dbConnection) throws SQLException
{
try
{
if(dbConnection != null)
{
dbConnection.close();
log.info("DB2 Connection closed.");
} // End IF
} // End TRY
catch(SQLException e)
{
log.error("Exception ---> " +e.getMessage());
}
}
} // End Class Definition
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
/*
* *@Rakesh K
*
*/
public class DB2Connect
{
public static Logger log=Logger.getLogger(DB2Connect.class);
public static Connection getConnection(String dataSourceName) //here dataSourceName is JNDI name
{
log.info("Enter [DB2Connect]getConnection()");
log.info("Data Source Name is: "+dataSourceName);
Connection dbConnection=null;
try{
InitialContext ctx = new InitialContext();
Object objRef = ctx.lookup(dataSourceName);
DataSource dataSource = (DataSource)objRef;
dbConnection = dataSource.getConnection();
}catch(SQLException ex){
log.error("Exceptio found at [DB2Connect]getConnection():"+ex);
}catch(NamingException ex){
log.error("Exceptio found at [DB2Connect]getConnection():"+ex);
}catch(Exception ex){
log.error("Exceptio found at [DB2Connect]getConnection():"+ex);
}
return dbConnection;
}
public static void closeConnection(Connection dbConnection) throws SQLException
{
try
{
if(dbConnection != null)
{
dbConnection.close();
log.info("DB2 Connection closed.");
} // End IF
} // End TRY
catch(SQLException e)
{
log.error("Exception ---> " +e.getMessage());
}
}
} // End Class Definition