
在 node.js 中使用 sequelize 进行事务回滚
在尝试使用 sequelize 执行事务回滚时,查询操作可能并未真正撤消。下文介绍了此问题可能的原因和解决方案。
问题原因
导致事务回滚失败的原因与数据库的存储引擎有关。默认情况下,mysql 中的 innodb 表支持事务处理,而 myisam 表不支持。如果使用的表不是 innodb 表,则回滚操作将不起作用。
解决方案
要解决此问题,需将表存储引擎更改为 innodb。具体步骤如下:
- 连接到 mysql 数据库。
- 运行以下命令查看表的存储引擎:
show table status like 'your_table_name'
- 如果存储引擎不是 innodb,请运行以下命令将其更改为 innodb:
alter table your_table_name engine=innodb
- 确认存储引擎已更改为 innodb:
show table status like 'your_table_name'
代码示例
修改表的存储引擎:
alter table groups engine=innodb;
修改后的代码应如下所示:
exports.createGroup = async function (user_id, name, img_url) {
const t = await sequelize.transaction();
try {
let result = await models(sequelize).groups.create({
user_id: user_id,
name: name,
img_url: img_url
}, { transaction: t });
await t.rollback();
console.log('回滚');
return func.resJsonSuccess(result, '建群成功!');
} catch (error) {
return func.resJsonError([], error.message);
}
};










