Enter your keyword

post

Java Jndi datasource lookup

JNDI style is typical when using an application server(Weblogic, JBOSS) or a web container(Apache Tomcat).

Here’s a example of the lookup Datasource created in Server.

import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class DatabaseConnection {
    public DatabaseConnection() {
        super();
    }
    // JNDI name created in Server

    final static String DATA_SOURCE=”jdbc/PortalDS”;
    public static void main(String[] args) {

        Connection connection = DatabaseConnection.init(DATA_SOURCE);
      
        System.out.println(“Connection “+connection);

    }
  
    private static Connection init(String dsName) {
              Connection con = null;
              DataSource datasource = null;
     
              Context initialContext = null;
              try{
                initialContext = new InitialContext();
                if (initialContext == null) {
                }
                datasource = (DataSource)initialContext.lookup(dsName);
                if (datasource != null) {
                     con = datasource.getConnection();
                } else {
                    System.out.println(“Failed to lookup datasource.”);

                }
              }catch (SQLException sqle) {
                     System.out.println(“SQL Exception occurred while getting DataSource : ” +
                               sqle);
                   
                 } catch (NamingException ne) {
                     System.out.println(“Naming Exception occurred while getting DataSource : ” +
                               ne);
              

                 }
           
              return con;
          }
}

One Comment

  1. added on 18 Jul, 2019
    Reply

Leave a Reply

Your email address will not be published.