Tuesday, 5 February 2013

Connection pooling | Java J2EE Tutorial pdf

Connection pooling

DataSource are currently the preferred method for obtaining database connections. The data source interface provides a more flexible architecture than using DriverManager for creating & using Database connections. By using a datasource object to obtain a connection, we can access different databases without a single change in our client code. The data source hides the connection details as that we, as the Client programmer, never need to worry about the connection URL, host, port & soon.
A connection pool provides a pool of precreated database connections. This avoids the time consuming activity of creating a new connection to a database. On the client side, there is little to do difference in how the connection is used. The difference lies in how connections are created, handed out and returned to the pool.
Next listing uses a datasource and pool that is configured on weblogic server:
import java.sql.*;
import javax.sql.*;
import javax.naming.*;
import java.util.*;
public class PoolDemo{
public static void main(String a[]) throws Exception {
Properties p=new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory"
);
p.put(Context.PROVIDER_URL,"t3://localhost:7001");
Context ctx=new InitialContext(p);
DataSource ds=(DataSource)ctx.lookup("jm_ds_jndi");
Connection con=ds.getConnection();
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from EMP");
while(rs.next()) {
System.out.println("NAME "+rs.getString(1)+"ID
"+rs.getInt(2));
}
}
}

No comments: