2017-06-22 66 views
0

我一直在試圖製作一個簡單的表格,然後在其中插入數據以開發一種理解,即Ionic 2框架如何工作,但我遇到了問題並無法解決問題。我嘗試了不同的谷歌解決方案,但他們都沒有工作。Ionic 2數據庫類型錯誤:executeSql

注:我是新來的Ionic 2和最初的本地Android開發人員。

import { Component } from '@angular/core'; 
import { IonicPage, NavController, NavParams, ToastController, Platform } from 'ionic-angular'; 
import { SQLite, SQLiteObject } from '@ionic-native/sqlite'; 
/** 
* Generated class for the AddProductsPage page. 
* 
* See http://ionicframework.com/docs/components/#navigation for more info 
* on Ionic pages and navigation. 
*/ 
@IonicPage() 
@Component({ 
    selector: 'page-add-products', 
    templateUrl: 'add-products.html', 

}) 
export class AddProductsPage { 
    productName: string; 
    sqlstorage: SQLite; 
    items: Array<Object>; 
    db: SQLiteObject; 
    mesg: string; 
    constructor(public navCtrl: NavController, public navParams: NavParams, private toastCtrl: ToastController, public platform: Platform) { 


    this.platform.ready().then(() => { 
     this.sqlstorage = new SQLite(); 

     this.sqlstorage.create({ name: "test.db", location: "default" }).then(() => { 
     console.log("SuccessDB"); 
     this.db.executeSql("CREATE TABLE IF NOT EXISTS product (ProductID INTEGER PRIMARY KEY AUTOINCREMENT, ProductName TEXT)", []); 
     // this.createTables(); 
     }, (err) => { 
     console.log("DB !!! ", err); 
     }); 
    }); 
    } 
    presentToast() { 
    let toast = this.toastCtrl.create({ 
     message: this.mesg, 
     duration: 3000, 
     position: 'top' 
    }); 

    toast.onDidDismiss(() => { 
     console.log('Dismissed toast'); 
    }); 

    toast.present(); 
    } 
    addProduct() { 


    this.addItem("insert into product (productName) values(?)", this.productName); 
    this.findAll(); 
    } 

    public createTables() {  
    this.db.executeSql("CREATE TABLE IF NOT EXISTS product (ProductID INTEGER PRIMARY KEY AUTOINCREMENT, ProductName TEXT)", []); 
    } 

    public addItem(q: string, param: string) { 
    this.db.executeSql(q, param).then((data) => { 
     console.log("Success"); 
    }, (e) => { 
     console.log("Error : " + JSON.stringify(e.err)); 
    }); 
    } 

    public findAll() { 
    this.db.executeSql("SELECT * FROM items", []).then((data) => { 
     this.items = []; 
     if (data.rows.length > 0) { 
     for (var i = 0; i < data.rows.length; i++) { 
      this.items.push(data.rows.item(i)); 
      this.mesg = data.rows.item(i); 
      console.log(this.mesg); 
     } 
     } 
    }, (e) => { 
     this.mesg = "Errot: " + JSON.stringify(e); 
     console.log("Errot: " + JSON.stringify(e)); 
    }); 
    this.presentToast(); 
    } 
} 

繼承人從裝置的故障

OPEN database: test.db SQLitePlugin.js:175 
new transaction is waiting for open operation SQLitePlugin.js:106 
OPEN database: test.db - OK 
ERROR 
Error {rejection: TypeError, promise: t, zone: r, task: t} 
message: "Uncaught (in promise): TypeError: Cannot call method 'executeSql' of undefined↵TypeError: Cannot call method 'executeSql' of undefined↵ at AddProductsPage.createTables (file:///android_asset/www/build/main.js:58248:17)↵ at file:///android_asset/www/build/main.js:58226:23↵ at t.invoke (file:///android_asset/www/build/polyfills.js:3:9283)↵ at Object.inner.inner.fork.onInvoke (file:///android_asset/www/build/main.js:4649:37)↵ at t.invoke (file:///android_asset/www/build/polyfills.js:3:9223)↵ at r.run (file:///android_asset/www/build/polyfills.js:3:4452)↵ at file:///android_asset/www/build/polyfills.js:3:14076↵ at t.invokeTask (file:///android_asset/www/build/polyfills.js:3:9967)↵ at Object.inner.inner.fork.onInvokeTask (file:///android_asset/www/build/main.js:4640:37)↵ at t.invokeTask (file:///android_asset/www/build/polyfills.js:3:9888)" 
promise: t 
rejection: TypeError 
stack: (...) 
get stack: function() { [native code] } 
set stack: function() { [native code] } 
task: t 
zone: r 
__proto__: d 
main.js:1584 
defaultErrorLogger main.js:1584 
ErrorHandler.handleError main.js:1644 
IonicErrorHandler.handleError main.js:117966 
onError.subscribe.next main.js:5278 
schedulerFn main.js:4351 
SafeSubscriber.__tryOrUnsub main.js:15685 
SafeSubscriber.next main.js:15632 
Subscriber._next main.js:15572 
Subscriber.next main.js:15536 
Subject.next main.js:18926 
EventEmitter.emit main.js:4337 
NgZone.triggerError main.js:4709 
inner.inner.fork.onHandleError main.js:4670 
t.handleError polyfills.js:3 
r.runGuarded polyfills.js:3 
(anonymous function) polyfills.js:3 
n.microtaskDrainDone polyfills.js:3 
o 

編輯:

代碼錯誤而無法執行插入查詢。 (addProduct方法在點擊觸發器上執行。)

import { Component } from '@angular/core'; 
import { IonicPage, NavController, NavParams, ToastController, Platform } from 'ionic-angular'; 
import { SQLite, SQLiteObject } from '@ionic-native/sqlite'; 
/** 
* Generated class for the AddProductsPage page. 
* 
* See http://ionicframework.com/docs/components/#navigation for more info 
* on Ionic pages and navigation. 
*/ 
@IonicPage() 
@Component({ 
    selector: 'page-add-products', 
    templateUrl: 'add-products.html', 

}) 
export class AddProductsPage { 
    productName: string; 
    sqlstorage: SQLite; 
    items: Array<Object>; 
    db: SQLiteObject; 
    mesg: string; 
    constructor(public navCtrl: NavController, public navParams: NavParams, private toastCtrl: ToastController, public platform: Platform) { 


    this.platform.ready().then(() => { 
     this.sqlstorage = new SQLite(); 
     this.sqlstorage.create({ 
     name: 'data.db', 
     location: 'default' 
     }).then((db: SQLiteObject) => { 
     this.db = db; 
     console.log("Opened"); 

     db.executeSql("CREATE TABLE IF NOT EXISTS product (ProductID INTEGER PRIMARY KEY AUTOINCREMENT, ProductName TEXT)", []); 
     db.executeSql("insert into product (ProductID,ProductName) values(3,'jhkj')", []); 

     }).catch(e => { 
     console.log(e); 
     }); 
    }); 
    } 
    presentToast() { 
    let toast = this.toastCtrl.create({ 
     message: this.mesg, 
     duration: 3000, 
     position: 'top' 
    }); 

    toast.onDidDismiss(() => { 
     console.log('Dismissed toast'); 
    }); 

    toast.present(); 
    } 


    addProduct() { 
     // this.sqlstorage = new SQLite(); 


// this.sqlstorage.create({ 
    // name: 'data.db', 
    // location: 'default' 
    // }).then((db: SQLiteObject) => { 
    // console.log("Opened"); 
    return new Promise((resolve, reject) => { 
     this.db.executeSql("insert into product (productName) values(?)", this.productName).then((data) => { 
     resolve(data); 
     console.log("resolve"); 
     }, (error) => { 
     reject(error); 
     console.log("reject"); 
     }); 
    }); 
    // this.addItem("insert into product (productName) values(?)", this.productName, db); 
    // this.findAll(db); 
    // }).catch(e => { 
    // console.log(e); 
    // }); 

    } 

    public createTables() { 
    this.db.executeSql("CREATE TABLE IF NOT EXISTS product (ProductID INTEGER PRIMARY KEY AUTOINCREMENT, ProductName TEXT)", []); 
    } 

    public addItem(q: string, param: string, db: SQLiteObject) { 
    db.executeSql(q, param).then((data) => { 
     console.log("Success"); 
    }, (e) => { 
     console.log("Error : " + JSON.stringify(e.err)); 
    }); 
    } 

    public findAll(db: SQLiteObject) { 
    db.executeSql("SELECT * FROM product", []).then((data) => { 
     this.items = []; 
     if (data.rows.length > 0) { 
     for (var i = 0; i < data.rows.length; i++) { 
      this.items.push(data.rows.item(i)); 
      this.mesg = data.rows.item(i); 
      console.log(this.mesg); 
     } 
     } 
    }, (e) => { 
     this.mesg = "Errot: " + JSON.stringify(e); 
     console.log("Errot: " + JSON.stringify(e)); 
    }); 
    this.presentToast(); 
    } 
} 

回答

1

由於您嘗試使用未初始化的SQLiteObject數據庫,因此發生該錯誤。當你使用SQLite的create方法時,它會返回一個SQLiteObject,你可以用它來執行你的SQL查詢。這裏是一個例子 -

this.sqlite.create({ 
     name: 'data.db', 
     location: 'default' 
    }).then((db: SQLiteObject) => { 
     console.log("Opened");   
     db.executeSql("CREATE TABLE IF NOT EXISTS product (ProductID INTEGER PRIMARY KEY AUTOINCREMENT, ProductName TEXT)", []); 
    }).catch(e => { 
     console.log(e);   
    }); 
+0

這真的對特定情況有效。但我不能做其他操作,如插入數據我試圖通過「db:sqliteobject」的實例,並試圖再次使用完整的代碼,並更改查詢「db.executeSql(」insert into product( productName)values(?)「,this.productName)」但我仍然收到「」不能調用undefined「」的方法'executeSql'。我怎麼解決這個問題? –

+0

您可以發佈代碼,以便我可以對發生了什麼問題進行視覺檢查嗎? – hemantv

+0

更新了說明中的代碼 –