Is it necessary to rollback if commit fails?

6 php mysql commit rollback

This seems like a simple enough question, yet I couldn't find any definitive answers specific for MySQL. Look at this:

$mysqli->autocommit(false); //Start the transaction
$success = true;    

/* do a bunch of inserts here, which will be rolled back and
   set $success to false if they fail */

if ($success) {
    if ($mysqli->commit()) {
        /* display success message, possibly redirect to another page */
    }
    else {
        /* display error message */
        $mysqli->rollback(); //<----------- Do I need this?
    }
}

$mysqli->autocommit(true); //Turns autocommit back on (will be turned off again if needed)

//Keep running regardless, possibly executing more inserts
Run Code Online (Sandbox Code Playgroud)

The thing is, most examples I have seen just end the script if commiting failed, either by letting it finish or by explicitly calling exit(), which apparently auto rolls back the transaction(?), but what if I need to keep running and possibly execute more database-altering operations later? If this commit failed and I didn't have that rollback there, would turning autocommit back on (which according to this comment on the PHP manual's entry on autocommit does commit pending operations) or even explicitly calling another $mysqli->commit() later on, attempt to commit the previous inserts again, since it failed before and they weren't rolled back?

I hope I've been clear enough and that I can get a definitive answer for this, which has been bugging me quite a lot.

Edit: OK, maybe I phrased my question wrong in that line comment. It's not really a matter of whether or not I need the rollback, which, as it was pointed out, would depend on my use case, but really what is the effect of having or not having a rollback in that line. Perhaps a simpler question would be: does a failed commit call discards pending operations or does it just leaves them in their pending state, waiting for a rollback or another commit?

小智 0

如果您不重复使用连接并且在事务失败后立即关闭连接,则关闭连接无论如何都会导致隐式回滚。

如果您要重新使用连接,则绝对应该进行回滚以避免与任何后续语句不一致。

如果您没有真正重用它,但它仍然处于阻塞状态(例如,保持打开状态几秒钟甚至几分钟,具体取决于您是否在网站上或 cronjob 上),请记住可能有许多并发连接正在进行。因此,如果您有一个非常大的事务,服务器需要将其保持在临时状态,这可能会消耗大量内存(例如,如果您正在进行影响大量列或表的主要数据库迁移),您绝对应该显式执行失败后回滚或关闭连接以进行隐式回滚。

另一个因素是=>如果您在不同的进程中有大量并发连接,它们可能会也可能不会看到事务的部分内容,即使事务尚未提交,具体取决于您正在使用的事务隔离级别。另请参阅: https://dev.mysql.com/doc/refman/8.0/en/innodb-transaction-isolation-levels.html