How many commits get rolledback when we call rollback?

super7egazi :

What is the behavior of rollback when we have 2 or more commits?

Connection conn= getConnection();

try{

doSomeInsertOrUpdateStep1(conn); //some sql update/insert using connection
conn.commit(); //step 1

doSomeInsertOrUpdateStep2(conn); //some sql update/insert using connection
conn.commit(); //step 2

//ERROR IS THROWN HERE AFTER SECOND COMMIT
} catch(Exception e){

   conn.rollback(); //what will be rolledback exactly step 1 or step2 or both?

}

If there is an error thrown after the second commit, I don't know what is expected to be rolled back in this scenario.

GMB :

From the Oracle documentation :

Use the COMMIT statement to end your current transaction and make permanent all changes performed in the transaction.

[...]

Until you commit a transaction: [...] You can roll back (undo) any changes made during the transaction with the ROLLBACK statement.

So basically your code works as follows :

  • run the first query : if it succeeds, then COMMIT it and continue ; else ROLLBACK (revert any uncommitted changes done before the first statement was executed) and stop (do not run the next statement)
  • run the second statement : if it succeeds then COMMIT, else ROLLBACK. Please note that, since a COMMIT was executed just before executing the statement, there will be nothing to ROLLBACK anyway.

I think the this logic can maybe be optimized. From my understanding, you might be looking to run both queries in a single transaction meaning : either both queries succeed and you want to COMMIT them, or if any fails and you want to ROLLBACK everything.

To implement that behavior, you would need to remove the first COMMIT (after the first query was executed successfully).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=152970&siteId=1