Flipkart Search

Sunday 25 August 2013

getting the DB connection from Weblogic datasource / JNDI

If you have any java/J2ee/ADF project deployed to a weblogic server and you have already created data source for DB connection. You can also get the DB connection in the java code for any specific task.
So here it goes.

public static Connection getConnection(String dsName) throws NamingException,
SQLException {
Connection con = null;
DataSource datasource = null;

Context 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.");
return con;

Remember this will create a new DB connection. So after getting the job done make sure you close this connection

1 comment: