eat*_*ode 3 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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
将 auto-commit 设置为false意味着语句的更改不会在执行后立即提交。然而,它并不[必然]影响 的行为close(),它可以选择提交或回滚未提交的数据。正如文档所述:
强烈建议应用程序在调用 close 方法之前显式提交或回滚活动事务。如果调用 close 方法并且存在活动事务,则结果是实现定义的。
换句话说,无论自动提交标志如何,您都应该在调用它之前始终显式地commit()或rollback()一个Connection对象: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
}
Run Code Online (Sandbox Code Playgroud)