18

I've been wondering if beginTransaction in node.js mysql uses multiple connections (if I have multiple queries inside the transaction) in a pool or is it only using a single connection until it is committed?

Pavindu
  • 2,684
  • 6
  • 44
  • 77
Edwin Bermejo
  • 432
  • 3
  • 5
  • 17

1 Answers1

46

A transaction cannot be shared by multiple database connections and is always limited to a single connection. The best approach would be to acquire a connection from the pool before you begin the transaction and release it after a rollback or a commit.

pool.getConnection(function(err, connection) {
    connection.beginTransaction(function(err) {
        if (err) {                  //Transaction Error (Rollback and release connection)
            connection.rollback(function() {
                connection.release();
                //Failure
            });
        } else {
            connection.query('INSERT INTO X SET ?', [X], function(err, results) {
                if (err) {          //Query Error (Rollback and release connection)
                    connection.rollback(function() {
                        connection.release();
                        //Failure
                    });
                } else {
                    connection.commit(function(err) {
                        if (err) {
                            connection.rollback(function() {
                                connection.release();
                                //Failure
                            });
                        } else {
                            connection.release();
                            //Success
                        }
                    });
                }
            });
        }    
    });
});
Siddharth Nayar
  • 836
  • 7
  • 6
  • 1
    so if have multiple queries inside a transaction, i need to release it only after commit or in a rollback? i don`t need to release it every success of query? correct me if i`m wrong, thank you so much – Edwin Bermejo Dec 18 '17 at 08:42
  • 1
    Yes, you only need to release it after a commit or a rollback since those are the only cases where you end the transaction. – Siddharth Nayar Dec 18 '17 at 09:48
  • This was very helpful to me. More upvotes to this please. – Darshan Jain Dec 26 '20 at 11:02