Node.js mysql transaction

前端 未结 7 1298
南笙
南笙 2020-12-13 16:16

Can anyone provide an example of how I could achieve MySQL transactions in Node.js. I am trying to get my head around using the node-mysql driver and node-mysql-queue.

相关标签:
7条回答
  • 2020-12-13 16:49

    I have come up with a solution using a recursive function.

    var sql = 'INSERT INTO logs SET data = ?';
    
    // array of rows to insert
    var rows = [[/*first row*/], [/*additional row*/]];
    
    connection.beginTransaction(function (err) {
    
        if (err) { 
            throw err; 
        }
    
        var insertEachRow = function () {
    
            var row = rows.shift();
    
            if (! row) {
                // Done, now commit
                return noMoreRows();
            }
    
            connection.query(sql, row, function (err, result) {
                if (err) { 
                    connection.rollback(function () {
                        throw err;
                    });
                }  
    
                insertEachRow();
            });
        };
    
        var noMoreRows = function () {
            connection.commit(function (err) {
                if (err) { 
                    connection.rollback(function () {
                        throw err;
                    });
                }
                console.log('success!');
            });
        };
    
        insertEachRow();
    });
    
    0 讨论(0)
提交回复
热议问题