sequelize事务封装,执行多句SQL

//sequelize 初始化
const Sequelize = require('sequelize');
const createNamespace = require('continuation-local-storage').createNamespace;
const namespace = createNamespace('sequelize-session');
Sequelize.useCLS(namespace);
var sequelize = new Sequelize(...)

//事务封装
async function dbTran(func) {
  return new Promise((resolve, reject) => {
    models.sequelize.transaction(async () => {
        return await func();
    }).then(result => {
      console.info(result);
      resolve(result);
    })
    .catch(e => {
      console.error(e);
      reject(e);
    });
  })
}

调用方式

//事务处理
      common.dbTran(async () => {
        await models.fk_cash.create({
          serialno: serialno,
          price: price,
          uid: userinfo.id,
          nickname: userinfo.nickname,
          tel: userinfo.tel,
          cash_type: cashType,
          fee: (price * fee).toFixed(2),
          start_time: start,
          role: 0,
          status: 10,
          account_info: account_info ? JSON.stringify(account_info) : ''
        })
        await models.fk_seller.update({
          balance: userinfo.balance - price
        }, {
          where: {
            id: userinfo.id
          }
        })
      }).then(()=>{
        this.success('ok')
      }).catch(err=>{
        this.error(err)
      })

这里需要注意的是,mysql数据库需要设置数据引擎为InnoDB

1.查看某个表使用的数据库引擎
show create table 表名;
 
2.查看mysql当前默认的数据库引擎
show variables like '%storage_engine%';
 
3.查看支持的引擎(没什么用,一般都支持innodb,一般都用innodb)
show engines;
 
4.修改表的数据库引擎
alter table 表名 engine=InnoDB;

 

金烽网络分享最优质的的资源,涵盖网站建设、IT技术、主题源码
金烽网络 » sequelize事务封装,执行多句SQL

3 评论

  1. Hi there. I found your web site by way of Google while looking for a related subject, your website got here up. It seems to be great. I have bookmarked it in my google bookmarks to visit then. Bert Cass Pinkerton

  2. Thank you for your entire labor on this web site. My mom really loves managing investigations and it is obvious why. My partner and i learn all regarding the lively method you offer practical strategies through this web site and even increase participation from some other people on the issue so our favorite girl is in fact learning a lot of things. Take advantage of the rest of the year. You are always doing a really good job. Marietta Woodie Byrdie

  3. Very nice post. I certainly love this site. Continue the good work! Marthena Ogden Dunseath

发表评论