Node.js mysql transaction

前端 未结 7 1328
南笙
南笙 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:40

    The following transaction example was added to the documentation a month ago:

    https://github.com/felixge/node-mysql#transactions

    connection.beginTransaction(function(err) {
      if (err) { throw err; }
      connection.query('INSERT INTO posts SET title=?', title, function(err, result) {
        if (err) { 
          connection.rollback(function() {
            throw err;
          });
        }
    
        var log = 'Post ' + result.insertId + ' added';
    
        connection.query('INSERT INTO log SET data=?', log, function(err, result) {
          if (err) { 
            connection.rollback(function() {
              throw err;
            });
          }  
          connection.commit(function(err) {
            if (err) { 
              connection.rollback(function() {
                throw err;
              });
            }
            console.log('success!');
          });
        });
      });
    });
    

提交回复
热议问题