Access data from application clients


To access a database directly from a J2EE application client, retrieve a DataSource object using resource references configured in the client deployment descriptor.

Not that client JDBC driver connections do not take advantage of the additional pooling support available in the appserver run time. For this reason, client applications should utilize EJBs running on the server side to take advantage of the connection reuse and additional added functionality provided by WAS run time.

  1. Import the appropriate JDBC API and naming packages

    import java.sql.*;
    import javax.sql.*;
    import javax.naming.*;

  2. Create the initial naming context

    InitialContext ctx = new InitialContext();

  3. Use the InitialContext to look up a data source object from a resource reference

    javax.sql.DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/myDS");  

  4. Get a java.sql.Connection from the data source.

    java.sql.Connection conn = ds.getConnection("user", "password"); 

  5. Run a database query...

    Statement xStatement = conn.createStatement();
    String query = "Select FirstNme from " 
                 + owner.toUpperCase() 
                 + ".Employee where LASTNAME = '" 
                 + searchName 
                 + "'";
    ResultSet xResultSet   = xStatement.executeQuery(query);
    while ( 

  6. Close the database objects used in the previous step, including any ResultSet, Statement, PreparedStatement, or CallableStatement objects.

  7. Close the connection. Ideally, close the connection in a finally block of the try...catch wrapped around the database operation. This action ensures that the connection gets closed, even in the case of an exception



See Also

Data sources
Configuring data access for application clients
Creating or changing a resource reference