问题描述
我正在将续集与Microsoft Azure sql数据库一起使用。我正在使用以下方法连接到数据库
let sequelize = new Sequelize(<DB_NAME>,<DB_USER>,<DB_PASS>,{
dialect: 'mssql',host: 'xxxxxx.database.windows.net',operatorsAliases: false,encrypt: true,timestamps: true
});
sequelize.authenticate().then(() => {
console.log('Connection established successfully.');
}).catch(err => {
console.error('Unable to connect to the database:',err);
})
这将建立连接。我想在我的SQL查询中使用事务。我使用以下代码对数据执行更新操作
const USERS= sequelize.define('USERS',<table details>);
await sequelize.transaction(async (t) => {
await USERS.update(
{ status: 'USER REMOVED' },{
where: { id: <ID>},returning: true,},{transaction : t}
)
throw "unsuccessful transaction"
}).then(async function(){
console.log("transaction successful")
}
).catch(err => {
console.error(err)
})
执行后,日志显示如下
Executing (b9f23ee86231fc03255b): BEGIN TRANSACTION;
Executing (b9f23ee86231fc03255b): ROLLBACK TRANSACTION;
转换为the transaction was rolled back
。
但是当我检查Azure sql数据库中的数据是否已更新时。
因此交易没有回滚。
我是否缺少某些东西或做错了什么? Azure sql支持事务吗?
解决方法
静态模型的update
方法只有两个参数:values
和options
,因此您应该在options
参数内传递事务:
await USERS.update(
{ status: 'USER REMOVED' },{
where: { id: <ID>},returning: true,transaction : t
}
)