node.js mysql池beginTransaction&联系 [英] node.js mysql pool beginTransaction & connection

查看:49
本文介绍了node.js mysql池beginTransaction&联系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直想知道node.js mysql中的 beginTransaction 是在池中使用多个连接(如果我在事务中有多个查询)还是仅使用单个连接直到提交?

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?

推荐答案

事务不能由多个数据库连接共享,并且始终仅限于单个连接.最好的方法是在开始事务之前从池中获取连接,并在回滚或提交后释放它.

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

这篇关于node.js mysql池beginTransaction&联系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆