在异常之后,即使AutoCommit为false,关闭Connection似乎也会提交事务

时间:2015-09-23 09:39:38

标签: java jdbc autocommit executequery

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();
            }
        }
    }

1 个答案:

答案 0 :(得分:3)

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

  

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

换句话说,无论自动提交标志如何,您都应该在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 } 个对象:

   =+IF(A2<>"";A1&A2&",";"")