Menu Close

Non-leaky query reads

Doing a select statement without leaking connections.

Pay special attention to the finally strategy:

  Connection conn = null;
  PreparedStatement stmt = null;
  ResultSet rs = null;
  try {
    conn = JDNIConnectionFactory.getJNDIConnection(dataSourceName);
    stmt = conn.prepareStatement("SELECT * FROM homeinv.Item ORDER BY item_id");
    rs = stmt.executeQuery();
    while ( rs.next() ) {
    	getItems().add(readItem(rs));
    }
  } catch ( Exception exc ) {
    exc.printStackTrace();
  } finally {
    try { if ( rs!= null) rs.close(); } catch (Throwable t) {}
    try { if ( stmt!= null) stmt.close(); } catch (Throwable t) {}
    try { if ( conn!= null) conn.close(); } catch (Throwable t) {}
  }