在mysql池中使用回滚
在接下来的教程中,我介绍了mysql库,它允许我使用在mysql池中使用回滚,mysql,node.js,Mysql,Node.js,在接下来的教程中,我介绍了mysql库,它允许我使用。然后而不是回调函数 以下是我对mysql池的设置: var mysql = require('mysql') var pool = mysql.createPool({ connectionLimit: 10, host: 'localhost', user: 'matt', password: 'password', database: 'my_d
。然后
而不是回调函数
以下是我对mysql池的设置:
var mysql = require('mysql')
var pool = mysql.createPool({
connectionLimit: 10,
host: 'localhost',
user: 'matt',
password: 'password',
database: 'my_database'
})
pool.getConnection((err, connection) => {
if (err) {
if (err.code === 'PROTOCOL_CONNECTION_LOST') {
console.error('Database connection was closed.')
}
if (err.code === 'ER_CON_COUNT_ERROR') {
console.error('Database has too many connections.')
}
if (err.code === 'ECONNREFUSED') {
console.error('Database connection was refused.')
}
}
if (connection) connection.release()
return
})
pool.query = util.promisify(pool.query)
module.exports = pool
这种设置使我的生活变得更加轻松,直到现在我还不知道如何处理回滚事务
我运行的查询如下:
pool.query('InsertQuery').then(rows=>{
return pool.query(`Select LocationID from Locations where LocationName = '${location[i]}'`)
})
.then(rows=>{
locationID =rows[0].LocationID
return pool.query(`Select StageID from Stages where StageName = '${stage[i]}'`)
})
.then('anotherInsert')....
.catch(err=>{
console.log(err)
})
当任何阶段出现错误时,执行中断时,末尾的catch块工作正常。但我希望能够回滚事务,并且在任何查询出现问题时不运行单个查询。有没有办法做到这一点?您必须在连接上开始一个事务,然后在所有工作完成后提交,或者在catch块中回滚。有关更多详细信息,请参阅此问题/答案:事务边界通常发生在比查询本身更高的级别。原因是使用事务通常表示需要运行多个查询,以便它们全部提交(或共享相同的隔离规则),或全部回滚。如果运行单个查询(默认情况下通常使用自动提交),则不需要显式回滚 有鉴于此,关于如何修改
query
方法以在不传递任何更高上下文(如txn)的情况下回滚自身的问题并不完全有意义。您通常会在某个更高级别启动事务,然后调用一个或多个查询,最后提交。或者,如果任何查询发生任何错误,则回滚。因此,您可以选择在查询方法中简单地抛出错误,并在更高级别上处理txn
psuedo代码示例:
conn = getConnection
.then
beginTxn
runQuery1
runQuery2
commitTxn
.catch
rollbackTxn
.finally
releaseConn
Fwiw,有一些库用于包装mysql库函数,其中包含可能感兴趣的承诺。示例:提交的
在哪里?可能是.catch
中的回滚
?“每次查询后连接都会自动释放”-这听起来像是交易的坏消息。不确定这是否有帮助: