我正在尝试执行总共有三个查询的node-mysql事务。这三个都是“ INSERT”查询。我故意将第三个查询写错以测试回滚,但是对于前两个查询,事务正在成功进入数据库。
我知道类似的问题已经问过好几次了,我几乎尝试了所有问题,但是没有运气
exports.registerNewUserTransaction = async (
res,
userToBeAdded,
nameToBeAdded,
emailToBeAdded) => {
const conn = await db.getConnection();
await conn.beginTransaction();
try {
await this.insertOne('user', userToBeAdded);
await this.insertOne('name', nameToBeAdded);
await this.insertOne('email', emailToBeAdded);
await conn.commit();
res.status(200);
} catch(err) {
await conn.rollback();
res.status(400);
} finally {
await conn.release();
}
};
如您所见,我正在从Pool获取连接对象,开始事务并逐个执行查询。我的第三个查询的列名错误,因此事务应回滚,但我看到前两个查询的条目。我非常感谢正确的方向。 节点版本:12.8.0 mysql(在docker中运行):8.0.15 mysql(npm版本):2.17.1
答案 0 :(得分:0)
经过很多努力,终于弄明白了。答案是这样:
exports.registerNewUserTransaction = async (
res,
userToBeAdded,
nameToBeAdded,
emailToBeAdded) => {
const conn = await db.getConnection();
// My first mistake was not to promisify connection query
conn.query = util.promisify(conn.query);
await conn.beginTransaction();
try {
// My second mistake was not to use same connection
await conn.query('INSERT INTO ...', userToBeAdded);
await conn.query('INSERT INTO ...', nameToBeAdded);
await conn.query('INSERT INTO ...', emailToBeAdded);
await conn.commit();
return res.status(200);
} catch(err) {
await conn.rollback();
return res.status(400);
} finally {
await conn.release();
}
};
希望这可能对某人有所帮助!