繁体   English   中英

JDBC 事务错误处理

[英]JDBC Transaction error handling

有关将事务与 jdbc 一起使用文档建议使用以下代码

public void updateCoffeeSales(HashMap<String, Integer> salesForWeek)
    throws SQLException {

    PreparedStatement updateSales = null;
    PreparedStatement updateTotal = null;

    String updateString =
        "update " + dbName + ".COFFEES " +
        "set SALES = ? where COF_NAME = ?";

    String updateStatement =
        "update " + dbName + ".COFFEES " +
        "set TOTAL = TOTAL + ? " +
        "where COF_NAME = ?";

    try {
        con.setAutoCommit(false);
        updateSales = con.prepareStatement(updateString);
        updateTotal = con.prepareStatement(updateStatement);

        for (Map.Entry<String, Integer> e : salesForWeek.entrySet()) {
            updateSales.setInt(1, e.getValue().intValue());
            updateSales.setString(2, e.getKey());
            updateSales.executeUpdate();
            updateTotal.setInt(1, e.getValue().intValue());
            updateTotal.setString(2, e.getKey());
            updateTotal.executeUpdate();
            con.commit();
        }
    } catch (SQLException e ) {
        JDBCTutorialUtilities.printSQLException(e);
        if (con != null) {
            try {
                System.err.print("Transaction is being rolled back");
                con.rollback();
            } catch(SQLException excep) {
                JDBCTutorialUtilities.printSQLException(excep);
            }
        }
    } finally {
        if (updateSales != null) {
            updateSales.close();
        }
        if (updateTotal != null) {
            updateTotal.close();
        }
        con.setAutoCommit(true);
    }
}

但是,错误处理对我来说似乎是错误的?

如果 try 块中存在 NullPointerException,则不会被捕获。 相反,执行将直接进入 finally 块,在那里它将调用con.setAutoCommit(true)根据文档将提交任何正在进行的事务。 似乎这显然不是预期的行为,因为它提交了一个不完整的事务。

我认为这可能只是示例中的一个错误,但其他教程也忘记捕获 SqlException 之外的异常( 进一步示例)。

我误解了发生了什么吗?

在调用con.setAutoCommit(true)之前,该示例关闭了可能未完成的准备语句。 因此,当切换回自动提交模式时,这些语句将不会被执行。 不会在那里提交不完整的事务。

我检查了您链接的第一个教程,它犯了不使用 finally 块、不取消未完成的语句和不恢复自动提交模式的错误。 看来真是不小心。

一般来说,我建议坚持使用官方教程,或者你真正信任的来源。

我倾向于认为你是对的; 我对此的解决方案是前段时间编写以下类,该类在引发意外异常时正确回滚。 作为奖励,您可以将事务包装在 try-with-resources 块中,我发现它更具可读性且易于使用。

你像这样使用它:

try(Transaction trans = Transaction.create(conn)) {
  // execute multiple queries, use trans.getConn()
  trans.commit();
} catch (SQLException e) {
  // Handle exception, transaction is safely rolled-back and closed
}
// No need for a finally block, or to catch RuntimeException.

这是完整的课程:

import static com.google.common.base.Preconditions.checkState;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * A Transaction can be used in a try-with-resources block to ensure a set of queries are
 * executed as a group.
 * 
 * try(Transaction trans = Transaction.create(conn)) {
 *   // execute multiple queries, use trans.getConn()
 *   trans.commit();
 * } catch (SQLException e) {
 *   // Handle exception, transaction is safely rolled-back and closed
 * }
 */
public final class Transaction implements AutoCloseable {
    private Connection conn;
    private boolean committed = false;
    private boolean rolledback = false;

    /**
     * Create a Transaction on the current connection, use to create
     * a try-with-resources block.
     * 
     * Note that if a transaction is started while another transaction is
     * ongoing (i.e. conn.getAutoCommit() == true) the earlier transaction
     * is committed. 
     */
    public static Transaction start(Connection conn) throws SQLException {
        return new Transaction(conn);
    }

    private Transaction(Connection conn) throws SQLException {
        this.conn = conn;
        // this is a no-op if we're not in a transaction, it commits the previous transaction if we are
        this.conn.setAutoCommit(true);
        this.conn.setAutoCommit(false);
    }

    /**
      * Call once all queries in the transaction have been executed,
      * to indicate transaction is complete and ready to be committed.
      * Should generally be the last line in the try block. 
     */
    public void commit() throws SQLException {
        if(committed) {
            throw new SQLException("Cannot commmit a transaction more than once");
        }
        if(rolledback) {
            throw new SQLException("Cannot commit a previously rolled-back transaction");
        }
        committed = true;
        getConn().commit();
    }

    /**
     * Call explicitly to cancel the transaction, called implicitly
     * if commit() is not called by the time the Transaction should
     * be closed.
     */
    public void rollback() throws SQLException {
        if(rolledback) {
            throw new SQLException("Cannot rollback a transaction more than once");
        }
        if(committed) {
            throw new SQLException("Cannot rollback a previously committed transaction");
        }
        rolledback = true;
        getConn().rollback();
    }

    /**
     * Should not be called directly, called in the try-with-resources
     * finally block to close the transaction.
     */
    @Override
    public void close() throws SQLException {
        try {
            if(!committed && !rolledback) {
                conn.rollback();
                throw new SQLException("Should explicitly rollback or commit transaction, rolling-back");
            }
        } finally {
            conn.setAutoCommit(true);
            conn = null;
        }
    }

    /**
     * Returns the Connection being used for this transaction.  You are encouraged
     * to use this method to access the transactional connection while inside the
     * transaction's try-with-resources block.
     */
    public Connection getConn() {
        checkState(conn != null, "Connection has already been closed");
        return conn;
    }
}

我还没有开源这个课程所属的项目,但如果有人需要,我很乐意在 MIT 许可下明确发布它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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