skip to main content
Using the JDBC Client : J2EE Connector Architecture Resource Adapter : Using the Resource Adapter from an Application
 

Using the Resource Adapter from an Application

The JCA resource adapter may also be used directly from an application, rather than through a container-managed, application server environment. The following code example shows how you might access a database using the resource adapter:
package examples;
 
import java.util.Hashtable;
import java.sql.Connection;
import javax.sql.DataSource;
import javax.naming.*;
import javax.resource.spi.*;
import com.ddtek.resource.oajdbc.JCAConnectionFactory;
import com.ddtek.resource.oajdbc.spi.*;
 
public class RAExample {
static public void main(String[] args) {
try {
// Create a connection factory instance
OpenAccessManagedConnectionFactory managedFactory =
new OpenAccessManagedConnectionFactory();
managedFactory.setServerName("MyServer");
managedFactory.setPortNumber("1521");
JCAConnectionFactory factory = (JCAConnectionFactory)
 
managedFactory.createConnectionFactory();
// Get an InitialContext. Using File System JNDI Service
// Provider as an example
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.fscontext.RefFSContextFactory");
env.put(Context.PROVIDER_URL,
"file:c:/ConnectionFactories");
Context connectorContext = new InitialContext(env);
// Bind the connection factory
try {
connectorContext.bind("ConnectionFactory", factory);
} catch (NameAlreadyBoundException except) {
connectorContext.rebind("ConnectionFactory", factory);
}
} catch (Exception except) {
System.out.println("Error creating DataSource");
System.exit(0);
}
// Connect via the DataSource
try {
// Get an InitialContext. Using File System JNDI Service
// Provider as an example
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.fscontext.RefFSContextFactory");
env.put(Context.PROVIDER_URL,
"file:c:/ConnectionFactories");
Context connectorContext = new InitialContext(env);
// Lookup the connection factory
DataSource dataSource = (DataSource)
 
connectorContext.lookup("ConnectionFactory");
Connection connection =dataSource.getConnection("john", "Be4ch");
catch (Exception except) {
System.out.println("Error looking up connection factory"); } }
}