node.js mysql pool beginTransaction & connection

前端 未结 1 1207
再見小時候
再見小時候 2021-02-20 04:06

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 usi

相关标签:
1条回答
  • 2021-02-20 04:10

    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
                            }
                        });
                    }
                });
            }    
        });
    });
    
    0 讨论(0)
提交回复
热议问题