Databse connection using Datasource

Database Connection using Data source:
Creating a database connection is expensive task because it requires establishing the connection over the network, connecting to the database and to connect to the database it also requires authentication process.

Using datasource the database connection to the database is made once and we will be asking weblogic to give us the datasource and using that datasource we can get the connection object using getConnection method.

Also the lookup for the datasource can be once done in init() method of the servlet and then we can use the datasource to get the connection anywhere in the doGet() or doPost() pethods.
For simplicity I am making simple stand alone java program.

Let’s first configure weblogic for Datasoruce.

Click on Services-->JDBC-->Datasource
Give any name and JNDI name then select appropriate database type.


Select Database Driver

Click Next

Provide Databse Name,Host Name, port , user name and password


Now if you want to check that the connection to the database is done or not simpley click test configuration.




Click Finish




Now lets write a simple java program to test the connecion.

package com.connect;

import java.sql.SQLException;
import java.sql.Statement;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;


public class TestDatasourse {

public static void main(String[] args) {
Context jndiContext = null;
DataSource dts=null;
java.sql.Connection con = null;
Statement stmt = null;
       java.sql.ResultSet rs = null;
try {
Hashtable properties = new Hashtable();
      properties.put(Context.INITIAL_CONTEXT_FACTORY,
                     "weblogic.jndi.WLInitialContextFactory");
      // NOTE: The port number of the server is provided in the next line,
      //       followed by the userid and password on the next two lines.
      properties.put(Context.PROVIDER_URL, "t3://localhost:7001");
      properties.put(Context.SECURITY_PRINCIPAL, "username");
      properties.put(Context.SECURITY_CREDENTIALS, "password");
jndiContext = new InitialContext(properties);
} catch (NamingException e) {
System.out.println("Could not create JNDI API " +
"context: " + e.toString());
System.exit(1);
}
try {
dts=(DataSource)
jndiContext.lookup("jdbc/ds");
} catch (NamingException e) {
System.out.println("JNDI API lookup failed: " +
e.toString());
System.exit(1);
}
try {
con=dts.getConnection();
String sql = "select * from customer";
stmt = con.createStatement( );
     

            rs = stmt.executeQuery(sql); 
            while(rs.next())
            {
             System.out.println(rs.getString(1));
            }
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println(e);
}finally
{
if (con != null) 
       try {
        con.close();
        } catch (SQLException e) {}
}
}

}

Sample O/P :