mysql事务

原生mysql操作

var mysql      = require('mysql');
var connection = mysql.createConnection(sqlServer);
 
connection.connect();
connection.beginTransaction(function(err) {
  connection.query('INSERT INTO `text1` SET title=?', 'title3', function (error, results, fields) {
    connection.commit()
    connection.rollback(function() {
      console.log('出现错误,回滚!');
    });
    connection.query('SELECT * FROM `text1`', function (error, results, fields) {
      if (error) throw error;
      console.log('The solution is: ', results);
    });
  })
})

使用第三方插件node-mysql-promise

var Mysql = require('node-mysql-promise');
var mysql = Mysql.createConnection(sqlServer);

mysql.startTrans().then(()=>{
  var data = {title: '订单9'};
  mysql.table('text1').add(data).then((insertId)=>{
      // mysql.rollback()
      //mysql.commit()
      var date = {title: '订单10'};
      mysql.table('text1').add(date).then((insertId)=>{
          //mysql.rollback()
          mysql.commit()

          mysql.query('SELECT * FROM `text1`').then(function (data) {
            console.log(data)
          })
      })
  })
})

  

  

posted @ 2020-05-10 01:02  fm060  阅读(130)  评论(0编辑  收藏  举报