This section describes options of using DataSource objects to create database connections.
As I mentioned earlier, there two different ways to create a connection object to access the database through a JDBC driver:
Using DrirverManager Class: DriverManager.getConnection(connection_url) - The driver manager passes the connection URL
to all loaded JDBC drivers, hoping that one of them will recognize the URL and creates a connection.
Using DataSource Object: ds.getConnection() - The JDBC driver provides DataSource classes, which can be initialized directly
or indirectly through JNDI (Java Naming and Directory Interface). A connection can be then created from the DataSource object.
The JDBC documentation suggests several options on how to use DataSource classes provided by the JDBC driver:
1. Using JDBC driver's DataSource classes directly without using JNDI. Here is a sample code:
AbcDataSource ds = new com.abc.jdbc.AbcDataSource();
ds.setServerName("someHost");
ds.setPortNumber("1527");
ds.setDatabaseName("someDB");
Connection con = ds.getConnection();
2. Using JDBC driver's DataSource classes indirectly through a JNDI directory service.
One example is to use Sun's File System Service Provider as shown in the sample code:
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.fscontext.RefFSContextFactory");
env.put(Context.PROVIDER_URL, "file:/temp");
Context ctx = new InitialContext(env);
// Storing a DataSource object
ClientDataSource dsIn
= new org.apache.derby.jdbc.ClientDataSource();
dsIn.setServerName("localhost");
dsIn.setDatabaseName("TestDB");
ctx.bind("DerbyTestDB", dsIn);
// Retrieving a DataSource object
DataSource dsOut = (DataSource) ctx.lookup("DerbyTestDB");