简体   繁体   中英

Java 7 exception handling with JDBC Connection and PreparedStatement?

In the following code-snippet,

1) Does the try-catch block automatically calls "conn.rollback()" before calling "conn.close()" (by AutoClose)? If not,do I have to add a finally { conn.rollback(); } finally { conn.rollback(); } to that block ?

2) Is the way Connection object passed in to the bar() method ,and the try-catch method in it correct?

public void foo() {
        try (Connection conn = datasource.getConnection()) {

            bar(conn, "arg");
            conn.commit();

        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    public void bar(Connection conn, String args) throws SQLException {
        try (PreparedStatement ps = conn.prepareStatement("SOME_QUERY")) {
            // Do something
            ps.executeUpdate();
        } catch (SQLException err) {
            throw err;
        }
    }

A try-with-resources will simply call the close() method on the Connection . The effect of calling Connection.close() when a transaction is active is implementation defined:

It is strongly recommended that an application explicitly commits or rolls back an active transaction prior to calling the close method. If the close method is called and there is an active transaction, the results are implementation-defined.

In other words: don't depend on it and explicitly call commit() or rollback() as the actual behavior will vary between drivers, maybe even between versions of the same driver.

Given your example I'd suggest:

public void foo() {
    try (Connection conn = datasource.getConnection()) {
        bar(conn, "arg");
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

public void bar(Connection conn, String args) throws SQLException {
    try (PreparedStatement ps = conn.prepareStatement("SOME_QUERY")) {
        // Do something
        ps.executeUpdate();
        conn.commit();
    } catch (SQLException err) {
        conn.rollback();
        throw err;
    }
}

Since you can't use conn in the catch or finally block of the try that created it, you could also nest it:

public void foo() {
    try (Connection conn = datasource.getConnection()) {
        try {
            bar(conn, "arg");
            conn.commit();
        } catch (Exception ex) {
            conn.rollback();
            throw ex;
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM