A DataSource object represents a particular DBMS or some other data source, such as a file. If a company uses more than one data source, it will deploy a separate DataSource object for each of them. In a native SQL environment the most of the response time is used in creating and managing the connections in the database. So the architects has introduced the connection pooling mechanism in which a pool of active connection is created at the startup of server or application and then all java programs will borrow the connection as and when required. The freeing or connections will be taken care by the pool itself so if user will not close the connection objects then it is done implicitly.


The below example will call the datasource in the weblogic server.


 


package com.visualbuilder;
import java.sql.Connection;
import java.util.Hashtable;


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


public class DataSourceExample {
    public static void main(String[] args) {
            Context ctx = null;
    try {
                Hashtable ht = new Hashtable();
        ht.put(Context.INITIAL_CONTEXT_FACTORY,
                    "weblogic.jndi.WLInitialContextFactory");
        ht.put(Context.PROVIDER_URL, "t3://localhost:7001");
        ctx = new InitialContext(ht);
                DataSource ds = (DataSource)ctx.lookup("DataSourcePool");
                Connection con = ds.getConnection();
                System.out.println("Connection Established");
        con.close();
                }catch(Exception exp)
                {
            exp.printStackTrace();
                }
        }
}


Output:-


Connection Established
                    

Copyright © 2013 VisualBuilder. All rights reserved