Is it a better practice to explicitly call transaction rollback or let an exception trigger an implicit rollback?

后端 未结 3 1059
孤街浪徒
孤街浪徒 2020-12-09 09:28

In the below code if any exception is thrown while executing the the SQL statements we should expect an implicit rollback on the transaction as the transaction was not commi

3条回答
  •  既然无缘
    2020-12-09 09:54

    You can go either way, the former being more concise, the latter being more intent revealing.

    A caveat with the first approach would be that calling RollBack on disposal of transaction is dependent on the driver specific implementation. Hopefully almost all the .NET connectors do that. SqlTransaction does:

    private void Dispose(bool disposing)
    {
        Bid.PoolerTrace(" %d#, Disposing\n", this.ObjectID);
        if (disposing && (this._innerConnection != null))
        {
            this._disposing = true;
            this.Rollback();
        }
    }
    

    MySQL's:

    protected override void Dispose(bool disposing)
    {
      if ((conn != null && conn.State == ConnectionState.Open || conn.SoftClosed) && open)
        Rollback();
      base.Dispose(disposing);
    }
    

    A caveat with second approach is it's not safe to call RollBack without another try-catch. This is explicitly stated in the documentation.

    In short as to which is better: it depends on the driver, but it's typically better to go for the first, for the reasons mentioned by Remus.

    Additionally see What happens to an uncommitted transaction when the connection is closed? for as to how connection disposal treat commits and rollbacks.

提交回复
热议问题