Magento 2: The way of using SQL transaction for low level operation

The way to guard unit operation of insert or update data in multiple tables and rollback if there is any error in the process

Posted on August 17, 2017 in Magento2

Magento 1:

The following code is used to perform Database Transaction so that the operation of some SQL query will be considered as unit. If there is any error occurred during these commands, the whole process will be rollback.

$connection = Mage::getSingleton('core/resource')->getConnection('core_write');


    //Make save actions

catch(Execption $e) {

Magento 2:

namespace Jeff\Lib\Helper;

use Magento\Framework\App\ResourceConnection;

class DbConnection {
    protected $_resource;
    protected $_dbConnection;

    protected function __construct(ResourceConnection $resource) {
        $this->_resource = $resource;
        $this->_dbConnection = $this->_resource->getConnection();

    public function Transaction() {

            //some save actions

        catch(\Exception $e) {

I hope these code snippet will help you in your future project when you update or insert data into multiple tables as Unit Operation.

comments powered by Disqus