java - 发生异常后,即使 AutoCommit 为 false,关闭连接似乎也会提交事务

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

最佳答案

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

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.

换句话说,无论自动提交标志如何,您都应该始终在 Connection 对象之前显式 commit()rollback() close()关闭它:

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 
 }

关于java - 发生异常后,即使 AutoCommit 为 false,关闭连接似乎也会提交事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32736040/

相关文章:

java - Java Synchronized(Object obj) 真正阻止了什么?

java - 无法为客户端形成正确的 JSON 响应

java - Dataprep - 当输出为 BigQuery 时数据流失败

java - ArrayBlockingQueue - 如何 "interrupt"正在等待 .take() 方法的线程

java - 从 Java 应用程序到 Oracle 的 jdbc 连接的自动提交模式

java - 如何实现JDBC驱动与源代码之间的松耦合?

java - 数据库池 - 在 Spring3 MVC 中连接到 Mysql 数据库

java - SQL java获取分配给自增主键的值

connection-pooling - 在 HikariCP 中连接时重置(自动提交)

SELECT 查询的 PostgreSQL 自动提交效率