I was asked (in private mail) for an example of using the new data source
facility in an actual application.  Since the Struts example doesn't use a real
database, I've extracted the following code snippet from one of my personal
webapps that uses this.  The code initializes a collection of domain table names
and values that will be used to populate select lists:

    ArrayList list = new ArrayList();
    DataSource ds =
      (DataSource) getServletContext().getAttribute(Action.DATA_SOURCE_KEY);
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try {
        conn = ds.getConnection();
        stmt = conn.prepareStatement("select org_id, name from organizations");
        rs = stmt.executeQuery();
        while (rs.next()) {
            DomainBean db =
             new DomainBean(rs.getInt(1), rs.getString(2));
            list.add(db);
        }
        rs.close();
        stmt.close();
        getServletContext().setAttribute("organizations", list);
    } catch (SQLException e) {
        ... deal with exception ...
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (SQLException f) {
            ... deal with exception ...
        }
    }

Note that I'm guaranteeing the connection that I allocated gets returned by
enclosing this logic in a "finally" block.

Craig

Reply via email to