gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:41:40 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com