3

setAutoCommit为 false 并在关闭连接之前引发异常,但仍会提交事务。这不是奇怪的行为吗?

public static void insertEmployee(){

        String query1 = "INSERT INTO EMPLOYEE VALUES(80, 'from code')";
        String query2 = "INSERT INTO EMPLOYEE VALUES(81, 'from code')";
        Connection connection = null;
        Statement statement = null;
        try {
            connection =   DriverManager.getConnection(url, username, password);
            connection.setAutoCommit(false);
            statement = connection.createStatement();
            statement.executeUpdate(query1);
            ResultSet resultSet = statement.executeQuery(query2);
            while(resultSet.next()) //this code throws the exception kept like this intentionally
            {
                int empNo = resultSet.getInt("EMPLOYEE_ID");
                String eName = resultSet.getString("EMPLOYEE_NAME");
                System.out.println("eName = " + eName);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                statement.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
4

1 回答 1

4

将 auto-commit 设置为false意味着语句的更改不会在执行后立即提交。但是,它不会 [必然] 影响 的行为close(),它可以选择提交或回滚未提交的数据。正如文档所述:

强烈建议应用程序在调用 close 方法之前显式提交或回滚活动事务。如果调用 close 方法并且存在活动事务,则结果是实现定义的。

换句话说,不管自动提交标志是什么,你都应该在 ing 之前明确地或commit()对象:rollback()Connectionclose()

try {
    // DML operations here

    // Explicitly commit if we got this far
    connection.commit();
} catch (SQLException e) {
    // If an exception occurred, explicitly rollback:
    connection.rollback();

    // Log somehow
    e.printStackTrace();
 } finally {
    // Close resources 
 }
于 2015-09-23T09:51:25.487 回答