2016-08-23 54 views
1

我有一個項目,其中有一個用於設置和查詢本地sqlite數據庫的服務。我使用了Ionic Native的cordova-sqlite-plugin和Sqlite。使用Sonicite從Ionic Native執行Ionic 2應用中的事務時出錯

這是我打開數據庫並在數據庫打開後創建表的代碼。

import {Injectable} from '@angular/core'; 
import {SQLite} from "ionic-native"; 

@Injectable() 
export class LocalDbService { 

sqlDb: SQLite; 

constructor() { 
    this.sqlDb = new SQLite(); 
} 

openDatabase() { 
    return this.sqlDb.openDatabase({ 
     name: 'app.db', 
     location: 'default' 
    }).then(() => { 
     return this.sqlDb.transaction((tx) => { 
      tx.executeSql(`create table if not exists groups (
       id nvarchar(50) primary key not null, 
       name nvarchar(50) unique not null, 
       createdOn datetime not null default current_timestamp, 
       updatedOn datetime not null default current_timestamp, 
       deleted boolean not null default 0 
      )`, []) 
     }) 
    }).catch((err) => { 
     console.error('Error while creating tables', err); 
    }) 
} 
} 

數據庫可以正常打開。但是,問題是創建表的事務總是拋出一個錯誤。在記錄錯誤的catch階段,它總是未定義的。

如果我執行一個簡單的executeSql方法而不是事務,它運行良好。我目前正在基於Android 6.0的設備上運行代碼。

我已閱讀Cordova s​​qlite插件中sql transactions的以下文檔以及Ionic本機中的Sqlite插件的文檔。

在Ionic 2上使用Sqlite交易的正確方法是什麼?

回答

0

我覺得你得到錯誤,因爲你不能夠訪問this.sqlDbthen你可以用下面如果openDatabase參考返回承諾在您打開的數據庫嘗試:

this.sqlDb.openDatabase({ 
    name: 'app.db', 
    location: 'default' 
}).then((db) => { 
    return db.transaction((tx) => { 
     tx.executeSql(`create table if not exists groups (
      id nvarchar(50) primary key not null, 
      name nvarchar(50) unique not null, 
      createdOn datetime not null default current_timestamp, 
      updatedOn datetime not null default current_timestamp, 
      deleted boolean not null default 0 
     )`, []) 
    }) 
}).catch((err) => { 
    console.error('Error while creating tables', err); 
}); 

或者,如果openDatabase沒有返回答應,那麼你必須通過數據庫是否打開或不喜歡檢查創建數據庫後創建的事務:

this.sqlDb.openDatabase({ 
    name: 'app.db', 
    location: 'default' 
}); 
if(this.sqlDb) { 
    this.sqlDb.transaction((tx) => { 
     tx.executeSql(`create table if not exists groups (
      id nvarchar(50) primary key not null, 
      name nvarchar(50) unique not null, 
      createdOn datetime not null default current_timestamp, 
      updatedOn datetime not null default current_timestamp, 
      deleted boolean not null default 0 
     )`, []) 
    }); 
} 
+0

this.sqlDb是許諾,裏面絕對可用>然後根據我使用箭頭福部分nctions。我甚至通過註銷來檢查它。它運行方法除了交易正常。當我調用事務方法時,它只會引發錯誤。這種行爲不僅在openDatabase承諾中。我使用它的任何地方,在使用交易時會引發錯誤。感謝您的幫助。 –

+0

我的項目中有同樣的行爲。不知何故交易不工作,他們應該如何。 –