如何在Ionic3上的SQLite插件中使用事务?

时间:2017-12-28 16:25:48

标签: sqlite typescript ionic-framework ionic2 ionic3

我想知道如何使用离子本机框架中的SQLite进行事务处理。我使用以下代码:

syncProducts(products: Array<Product>){
  if(this.networkService.isConnected()){
    this.database.create({name: "data.db.sqlite", location: "default"})
      .then(database => {
        console.log("Crear una transaccion");
        database.addTransaction(tx => {
          tx.start();
          console.log("TRANSACTION BEGIN -------");
          let productsForSync = products.filter(product => product.status == 1);
          for(var i = 0; i < productsForSync.length; i++){
            this.productService.sendProduct(productsForSync[i]).then(()=>{
              tx.executeSql("UPDATE product SET status = 2 WHERE id = "+productsForSync[i].id
                            ,[],data => {
                              console.log("data:"+data);
                            },error => {
                              console.log("Error in sql: "+error);
                            });
            }).catch(error => {
              console.error("Error from post: "+JSON.stringify(error));
            });
          }
        });
      });
    }else{
      console.log("No hay internet");
  }
}

但是日志“TRANSACTION BEGIN”没有被触发。我怎么用它?

此致

1 个答案:

答案 0 :(得分:0)

此示例显示如何在一个事务中连续运行promise chained sql操作:

// start transaction with `BEGIN`
return this.db.database.executeSql('BEGIN', [])
            .then(() => {
                // it return promise
                return this.promise1(products)
                    .then(res => {
                        // some operations
                        ...
                        return this.db.promise2(saleRow, 't_sale');
                    })
                    .then(resp => {
                        let saleId = resp.insertId;
                        return this.promise3(saleId, products);
                    })
                    .then(resp => {
                        ... 
                        return this.db.promise4(cashDeskRow, 't_cashdesks');
                    });
            })
            .then(data => {
                // after successfully finishing sql operations, `COMMIT` changes
                this.db.database.executeSql('COMMIT', []);
            })
            .catch(err => {
                // RollBack when error occurs
                this.db.database.executeSql('ROLLBACK', []);
            })

注意: this.db.database: SQLiteObject

另外,如果您在promise1 / promise2中发现错误...请记住返回return Promise.reject(err);以捕获事务级别承诺中的错误:

promise1(){
 return this.database.executeSql(statement, colValues)
      .then(data => {
        return data;
      }, err => {
        console.log('Error: ', err);
        return Promise.reject(err);
      });
}