diff --git a/utils/dbPoolUtils.js b/utils/dbPoolUtils.js index d50a32e..4aee356 100644 --- a/utils/dbPoolUtils.js +++ b/utils/dbPoolUtils.js @@ -65,6 +65,63 @@ async function query(sql, params) { }); } +// sqlParamsEntities = { sql: "", params: [], callback: function(可选) } +async function transaction(sqlParamsEntities) { + let connection; + try { + connection = await new Promise((resolve, reject) => { + pool.getConnection(function (err, connection) { + if (err) { + reject(err); + } + resolve(connection); + }); + }); + } catch (err) { + console.error("获取事务connection失败", err); + return; + } + + try { + return await new Promise((resolve, reject) => { + // 开启事务 + connection.beginTransaction(function (err) { + if (err) { + reject(err); + } + + // 开始执行SQL语句 + console.log("开始执行transaction,共执行" + sqlParamsEntities.length + "条数据"); + sqlParamsEntities.forEach((entity) => { + connection.query(entity.sql, entity.param, function (tErr, data) { + if (tErr) { + reject(tErr); + } + if (typeof entity.callback === 'function') + return entity.callback(data); + }) + }); + + // 执行完毕,提交事务 + connection.commit(function (tErr, info) { + console.log("transaction info: " + JSON.stringify(info)); + if (tErr) { + reject(tErr); + } + resolve(info); + }) + }); + }); + } catch (err) { + console.error("事务执行失败,开始回滚"); + connection.rollback(function () { + console.log("transaction error: " + err); + }); + } finally { + connection.release(); + } +} + async function close() { await new Promise((resolve, reject) => { if (!pool) return; @@ -76,7 +133,8 @@ async function close() { } module.exports = { - create: create, - query: query, - close: close, + create, + query, + transaction, + close, } \ No newline at end of file