node.js mysql pool beginTransaction & connection

纵然是瞬间 提交于 2020-12-29 09:49:10

问题


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?


回答1:


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
                        }
                    });
                }
            });
        }    
    });
});


来源:https://stackoverflow.com/questions/47809269/node-js-mysql-pool-begintransaction-connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!