//==================================================================== // ConnectionManager.java //==================================================================== package com.evident.database; import java.sql.*; import javax.sql.*; /** * Manages connections served by a JDBC DataSource, ensuring that * each connection is released after its use. */ public class ConnectionManager { /** Manages database connections. */ protected DataSource source; /** * Constructs a new ConnectionManager. * @param dataSource manages database connections. */ public ConnectionManager( DataSource dataSource ) { source = dataSource; } /** * Obtains a connection for a (usage) and frees the connection when * finished. Rolls back any uncommitted changes if a SQL exception is * thrown during the (usage) of the connection. * @param usage a database connection usage. * @exception java.sql.SQLException if an exception is thrown during the * connection (usage). */ public Object connectUsing( ConnectionUsage usage ) { boolean autoCommit = true; Connection connection = null; try { connection = source.getConnection(); usage.prepare( connection ); return usage.use( connection ); } catch( SQLException e ) { usage.rollback( connection ); e.printStackTrace(); return null; } finally { usage.release( connection ); } } }