ionic2数据库SQLite查询操作

1.安装插件:

$ ionic plugin add --save cordova-sqlite-storage

$ npm install --save @ionic-native/sqlite

2.在appMoudle注入

import { NgModule, ErrorHandler } from '@angular/core';
...
import { SQLite } from '@ionic-native/sqlite'

@NgModule({
  declarations: [
    MyApp,
   ...
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    HttpModule,
    JsonpModule
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    DevicePage,
    ContactPage,
    HomePage,
    TabsPage
  ],
  providers: [
   ...
    SQLite
  ]
})
export class AppModule {}
3.在指定页面应用:

import { Component, OnInit } from '@angular/core';
import { NavController } from 'ionic-angular';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite'

@Component({
	selector: 'page-contact',
	templateUrl: 'contact.html'
})
export class ContactPage implements OnInit {

	constructor(public navCtrl: NavController, private sqlite: SQLite) {}
	database: SQLiteObject;
	ngOnInit() {

		this.initDB();

	}

	initDB() {
		this.sqlite.create({
				name: 'data.db',
				location: 'default'
			}).then((db: SQLiteObject) => {
				db.executeSql('create table t_log(name VARCHAR(32))', {})
					.then(() => console.log('Executed SQL'))
					.catch(e => console.log(e));
				this.database = db;
				db.executeSql("insert into t_log values('123')", {});
			})
			.catch(e => console.log(e));
	}

	//查询
	query() {
		let result = this.database.executeSql("select * from t_log", [])
		.then((data) => {
			debugger;
			console.log("select->" + rs.rows.item(0).name)
			})
		.catch(e => console.log(e));
	}

}

你可能感兴趣的:(移动端)