Java 7 Automatic Resource Management JDBC (try-with-resources statement)

前端 未结 3 1061
长发绾君心
长发绾君心 2020-12-01 00:39

How to integrate the common JDBC idiom of creating/receiving a connection, querying the database and possibly processing the results with Java 7\'s automatic resource manage

3条回答
  •  抹茶落季
    2020-12-01 01:27

    If you want to use pooled connection in transaction, you should use it in this way:

    try (Connection conn = source.getConnection()) {
            conn.setAutoCommit(false);
            SQLException savedException = null;
            try {
                // Do things with connection in transaction here...
                conn.commit();
            } catch (SQLException ex) {
                savedException = ex;
                conn.rollback();
            } finally {
                conn.setAutoCommit(true);
                if(savedException != null) {
                    throw savedException;
                }
            }
        } catch (SQLException ex1) {
            throw new DataManagerException(ex1);
        }
    

    This sample code handles setting autocommit values.

    NOTE, that using savedException does save exception in case that conn.rollback() throws another. This way, finally block will throw "right" exception.

提交回复
热议问题