Home > Uncategorized > Magento DB transaction commit rollback sniplet

Magento DB transaction commit rollback sniplet

Took me a while to find out how to do this… as there was no good examples on the web.
So, here it is… so I can find it again.

keywords:
db database transaction rollback commit magento zend.

try {
    $write = Mage::getSingleton('core/resource')->getConnection('core_write');
    $write->beginTransaction();

// do stuff here

    $write->commit();
} catch (Exception $e) {
    mage::log(__METHOD__ . ':' . __LINE__ . ': Rollback happened.');
    $write->rollback();
}

Please drop a line if you found this useful. Thanks!

Categories: Uncategorized Tags:
  1. MP
    October 30th, 2011 at 15:28 | #1

    Thanks

  2. Soma
    February 13th, 2012 at 09:54 | #2

    Wouldn’t this give errors whenever you want to rollback because $write would be null. $write should be set outside the try catch construct.

  3. Lloyd Leung
    March 7th, 2012 at 17:44 | #3

    Soma :

    Wouldn’t this give errors whenever you want to rollback because $write would be null. $write should be set outside the try catch construct.

    No, the instance of $write will exist inside the catch statement.

    A quick test would show that rollback does in deed get triggered, when you throw an exception within the try statement.

  1. No trackbacks yet.