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.
- Import the appropriate JDBC API and naming packages
import java.sql.*;import javax.sql.*;
import javax.naming.*;- Create the initial naming context
InitialContext ctx = new InitialContext();- 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");- Get a java.sql.Connection from the data source.
java.sql.Connection conn = ds.getConnection("user", "password");
- 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 (xResultSet.next()) { firstNameList.addElement(xResultSet.getString(1)); }- Close the database objects used in the previous step, including any ResultSet, Statement, PreparedStatement, or CallableStatement objects.
- 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
conn.close();
See Also
Data sources
Configuring data access for application clients
Creating or changing a resource reference