sqlite - Cordova SQLite 事务不回滚

标签 sqlite cordova hybrid-mobile-app

我有以下代码用于混合移动应用程序中使用的数据库(由变量 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 时,必须遵循以下任一选项:

  1. 如果您确实提供错误回调,请确保它返回 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
    }
    
  2. 不要像下面的代码那样提供错误回调。如果您遵循此选项,您仍然可以提供成功回调。

    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/

相关文章:

android - 动态创建具有定义行的 SQLite 表

visual-studio - VS 2017 RC找不到cordova工具

android - Cordova FileTransfer 下载错误

android - PhoneGap 1.8.1 - 启动画面不起作用?

javascript - jQuery Mobile 在页面转换时闪烁

performance - 在cordova ionic中减少从冷启动开始的加载时间

java - 带字符串和 double 的 JFreechart

iphone - SQLite ANALYZE 破坏索引

c# - Log4Net-SQLite的AdoNetAppender无法插入

android - 为什么我在升级到 Cordova Android 8 后看到 net::ERR_CLEARTEXT_NOT_PERMITTED 错误?