Connecting to a Data Source

Applications must first be connected to a database before performing any database operation. As explained earlier, connections are made ready by the container, at startup, through the creation of a connection pool.

Connections are created using the DataSource object. Applications need to locate a DataSource object, before creating a Connection. Applications locate a DataSource through the JNDI service. The following is an example of these steps:

// Connect to the default JNDI service and establish a context
Context ctx = new InitialContext();
// Lookup the DataSource for the configured database
javax.sql.DataSource ds = (javax.sql.DataSource)
        ctx.lookup ("java:comp/env/jdbc/styejbDB");
// Make a connection to the database
java.sql.Connection conn = ds.getConnection();

// do some work

// Release the connection after you are done
conn.close();

Note

You must release the connection as soon as you have done work with it by closing the connection. When the client virtually closes the connection with close(), behind the scenes, the container returns the connection to the pool, and makes it available for use by other clients.


As recommended, JDBC DataSource references should always be declared in the java:comp/env/jdbc subcontext. This is established by the system administrator when the DataSource is being created.

Establishing a context to the JNDI service is an expensive operation, especially when using an RMI call. Always connect to the JNDI service to obtain a DataSource object in the initialization code of your application. This can be done once, and connection(s) can be assigned by the DataSource to other parts of the application during its lifetime.

Applications rely on the container to manage the connection pool, but when building scalable applications, releasing connections as soon as possible is the responsibility of the developer.

The traditional way of getting a connection is by using the DriverManager. As mentioned early today, this is a deprecated method, and we recommend using the DataSource method if possible. For the sake of completeness, the following snippet shows how to make a connection using the DriverManager:

String sourceURL = "jdbc:cloudscape:styejbPool";
String driverClass = "COM.cloudscape.core.JDBCDriver"
// Loading the JDBC driver
Class.forName(driverClass);
// Make a connection using the DriverManager
java.sql.Connection conn = DriverManager.getConnection(sourceURL);

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.113.163