99maas
99maas

Reputation: 1267

How to establish database connection by using dataSource in Weblogic

I need your help in establishing the connection to the weblogic dataSource. Earlier in the java bean, I am using the below code to establish the connection to the database:

PreparedStatement ps = null;
Connection con = null;

try {
     con = DriverManager.getConnection("jdbc:oracle:thin:@xx.xx.xx.xx:1521:xxx", "hr", "hr123");

      sql = " select * from employees";
      ps = con.prepareStatement(sql);
     }
catch (Exception e) {
      System.err.print(e);
      e.printStackTrace();
      } 

Now, I need to get the connection from weblogic datasource by using the JNDI name. I have created the dataSource and it is called jdbc/HR and I tried the below code, but I wasn't successful in establishing the connection:

Context ctx = null;
Hashtable ht = new Hashtable();
java.sql.Connection conn = null;
ht.put(Context.INITIAL_CONTEXT_FACTORY,  "weblogic.jndi.WLInitialContextFactory");
ht.put(Context.PROVIDER_URL,"t3://localhost:7001");

 try {
      ctx = new InitialContext(ht);
      javax.sql.DataSource ds = 
        (javax.sql.DataSource) ctx.lookup("demoDataSource");
      conn = ds.getConnection();
     }

Upvotes: -1

Views: 2662

Answers (1)

99maas
99maas

Reputation: 1267

This was solved by:

 Connection con = null;
 DataSource datasource = null;

 Context initialContext = new InitialContext();

 // "jdbc/MyDBname" >> is a JNDI Name of DataSource on weblogic

 datasource = (DataSource) initialContext.lookup("jdbc/MyDBname");

 con = datasource.getConnection();

Upvotes: 1

Related Questions