我有以下代码用于混合移动应用程序中使用的数据库(由变量 db 表示)。
SQLite 数据库中没有Customers 或Items 表,所以第三条和第四条SQL 语句抛出错误,但最终还是创建了Table1Backup 表。 为什么会发生这种情况,因为在这种情况下,在事务中应该发生隐式回滚?
db.transaction(function(tx) {
tx.executeSql("DROP TABLE if exists Table1Backup", [], success, error);
tx.executeSql("CREATE TABLE if not exists Table1Backup AS
SELECT * FROM Table1", [], success, error);
tx.executeSql("CREATE TABLE CustomersBackup AS SELECT * FROM Customers",
[], success, error);
tx.executeSql("CREATE TABLE ItemsBackup AS SELECT * FROM Items",
[], success, error);
});
}
function success(tx, result) {
alert("succeeded ");
}
function error(tx, err) {
alert("ERROR " + err.message);
}
最佳答案
我找到了答案。为了在错误时回滚事务,在基于 CORDOVA 的混合应用程序中使用 SQLITE 时,必须遵循以下任一选项:
如果您确实提供错误回调,请确保它返回 true。如果错误回调返回 false,则事务将不会回滚,之前的语句将自动提交。
db.transaction(function(tx) { tx.executeSql("DROP TABLE if exists Table1Backup", [], success, error); tx.executeSql("CREATE TABLE if not exists Table1Backup AS SELECT * FROM Table1", [], success, error); tx.executeSql("CREATE TABLE CustomersBackup AS SELECT * FROM Customers", [], success, error); tx.executeSql("CREATE TABLE ItemsBackup AS SELECT * FROM Items", [], success, error); }); } function success(tx, result) { alert("succeeded "); } function error(tx, err) { alert("ERROR " + err.message); return true;//THIS IS IMPORTANT FOR TRANSACTION TO ROLLBACK ON QUERY ERROR }
不要像下面的代码那样提供错误回调。如果您遵循此选项,您仍然可以提供成功回调。
db.transaction(function(tx) { tx.executeSql("DROP TABLE if exists Table1Backup"); tx.executeSql("CREATE TABLE if not exists Table1Backup AS SELECT * FROM Table1"); tx.executeSql("CREATE TABLE CustomersBackup AS SELECT * FROM Customers"); tx.executeSql("CREATE TABLE ItemsBackup AS SELECT * FROM Items"); }); }
关于sqlite - Cordova SQLite 事务不回滚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22287990/