在connection.setAutoCommit = false上会发生什么

eat*_*ode 4 java connection jdbc autocommit

如果我这样connection.setAutoCommit(false);做会在数据库端创建新的事务,该怎么办?

Mic*_*nic 7

根据文档connection.setAutoCommit(false)将允许您将同一事务下的多个后续s 分组Statement。此事务将在connection.commit()被调用时被提交,而不是execute()在单个Statements 上的每个调用之后被提交(如果启用了自动提交,则会发生此情况)。

通过更改自动提交模式connection.setAutoCommit()将隐式提交活动事务并创建一个新事务。从Javadocs

注意:如果在事务期间调用此方法,并且更改了自动提交模式,则提交事务。如果调用setAutoCommit且自动提交模式未更改,则该调用为无操作。


Nal*_*chu 5

让我用代码简单解释一下。当我们申请了

Connection.setAutoCommit(假);

在我们的源代码中,它将禁用自动提交选项,该选项默认在数据库中启用。

所以,你必须打电话

连接.commit();

方法显式地保存对数据库的任何更改。

Class.forName(drivers);
Connection dbConnnection=DriverManager.getConnection(connectionURL,username,password);
dbConnection.setAutoCommit(false); //Disabling the Autocommit
Statement selectStatement = dbConnection.createStatement("Select Query");
ResultSet rs = selectStatement.execute();
while(rs.next()){
    Statement updateStatement = dbConnection.createStatement("update Query");
    //Apply some changes to update record
    statement.execute();
    dbConnection.commit();  //Mandatory to execute to persist changes into database
}
Run Code Online (Sandbox Code Playgroud)