【发布时间】:2017-03-09 17:48:43
【问题描述】:
我想知道如何将 Sqlite 与 Ionic 2 rc.o 版本一起使用。我觉得很难,因为没有最新版本的示例,我被卡住了。网上似乎没有任何更新。A Sqlite 的支持示例将非常有用。 提前谢谢你。
【问题讨论】:
-
Nopes @mosca90 我在同一页上。
-
如果有效,你能接受答案吗? @Hrishikesh Kulkarni
我想知道如何将 Sqlite 与 Ionic 2 rc.o 版本一起使用。我觉得很难,因为没有最新版本的示例,我被卡住了。网上似乎没有任何更新。A Sqlite 的支持示例将非常有用。 提前谢谢你。
【问题讨论】:
1) 首先,导航到项目的根文件夹并添加插件:
$ ionic plugin add cordova-sqlite-storage
$ npm install --save @ionic-native/sqlite
2) 在项目中创建一个新的提供者(在本例中,名为 SqlStorage):
$ ionic g provider sqlStorage
3) 我想添加一个导入到 app.component.ts 以在启动时初始化插件,不是强制性的:
import {SqlStorage} from '../providers/sql-storage';
...
...
constructor(public sqlStorage: SqlStorage){}
4) 向 app.module.ts 添加条目,强制:
import { SQLite } from '@ionic-native/sqlite';
import { SqlStorage } from '../providers/sql-storage';
...
...
providers: [SQLite, SqlStorage]
5) 定义 sql-storage.ts 提供者:
import { Injectable } from '@angular/core';
import { Platform } from 'ionic-angular';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';
@Injectable()
export class SqlStorage {
storage: any;
DB_NAME: string = '__ionicstorage';
constructor(public platform: Platform, public sqlite: SQLite) {
this.platform.ready().then(() => {
this.sqlite.create({ name: this.DB_NAME, location: 'default' })
.then((db: SQLiteObject) => {
this.storage = db;
this.tryInit();
});
});
}
tryInit() {
this.query('CREATE TABLE IF NOT EXISTS kv (key text primary key, value text)')
.catch(err => {
console.error('Unable to create initial storage tables', err.tx, err.err);
});
}
/**
* Perform an arbitrary SQL operation on the database. Use this method
* to have full control over the underlying database through SQL operations
* like SELECT, INSERT, and UPDATE.
*
* @param {string} query the query to run
* @param {array} params the additional params to use for query placeholders
* @return {Promise} that resolves or rejects with an object of the form
* { tx: Transaction, res: Result (or err)}
*/
query(query: string, params: any[] = []): Promise<any> {
return new Promise((resolve, reject) => {
try {
this.storage.transaction((tx: any) => {
tx.executeSql(query, params,
(tx: any, res: any) => resolve({ tx: tx, res: res }),
(tx: any, err: any) => reject({ tx: tx, err: err }));
},
(err: any) => reject({ err: err }));
} catch (err) {
reject({ err: err });
}
});
}
/** GET the value in the database identified by the given key. */
get(key: string): Promise<any> {
return this.query('select key, value from kv where key = ? limit 1', [key])
.then(data => {
if (data.res.rows.length > 0) {
return data.res.rows.item(0).value;
}
});
}
/** SET the value in the database for the given key. */
set(key: string, value: string): Promise<any> {
return this.query('insert into kv(key, value) values (?, ?)', [key, value]);
}
/** REMOVE the value in the database for the given key. */
remove(key: string): Promise<any> {
return this.query('delete from kv where key = ?', [key]);
}
}
6) 在您的 .ts 页面中:
import {SqlStorage} from '../../providers/sql-storage';
export class ExamplePage {
constructor(public sqlStorage: SqlStorage) {
// this.sqlStorage.query(...);
// this.sqlStorage.get(key).then(data => {
// console.log(data);
// }
//...
}
}
感谢:https://github.com/NickStemerdink 并进行了一些个人更改。 希望它会有所帮助并且可以正常工作:)
编辑:仍然适用于 Ionic v3.0.1 (2017-04-06)
【讨论】:
this._db.transaction... 更改为this.storage.transaction...。我是新手,但运行代码会给我一个运行时错误:“Uncaught (in promise): [object Object]” using this.sql.set(...).
updatePackage(id: number, nota: string, data: string, time: string): Promise<any> { return this.query('UPDATE package SET nota = \"' + nota + '\", dtaVar = \"' + data + '\" WHERE id = ?', [id]); }
this.sqlStorage.query(...);
在 app.module.ts 中
import { SQLite } from '@ionic-native/sqlite';
providers: [
StatusBar,
SplashScreen,
SQLite,
{ provide: ErrorHandler, useClass: IonicErrorHandler }
]
在数据库提供程序中
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
//import { Storage } from '@ionic/storage';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';
import { Platform } from 'ionic-angular';
/*
Generated class for the Database provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
@Injectable()
export class Database {
DB_NAME: string = 'ssddb';
constructor(public http: Http, public platform: Platform, public sqlite: SQLite) {
this.platform.ready().then(() => {
this.configureDatabase();
});
}
configureDatabase() {
this.query('CREATE TABLE IF NOT EXISTS EMP (key text primary key, value text)')
.catch(err => {
console.error('Unable to create initial storage tables', err.tx, err.err);
});
}
query(query: string, params: any[] = []): Promise<any> {
return new Promise((resolve, reject) => {
try {
this.sqlite.create({
name: this.DB_NAME,
location: 'default'
})
.then((db: SQLiteObject) => {
db.transaction((tx: any) => {
tx.executeSql(query, params,
(tx: any, res: any) => resolve({ tx: tx, res: res }),
(tx: any, err: any) => reject({ tx: tx, err: err }));
})
})
.catch(e => console.log(e));
} catch (err) {
reject({ err: err });
}
});
}
get(key: string): Promise<any> {
return this.query('select key, value from EMP where key = ? limit 1', [key])
.then(data => {
if (data.res.rows.length > 0) {
return data.res.rows.item(0).value;
}
});
}
set(key: string, value: string): Promise<any> {
return this.query('insert into EMP(key, value) values (?, ?)', [key, value]);
}
}
在 page.ts 中
this.database.set("333","ss");
this.database.get("333").then(data => {
console.log(data);
let toast = this.toastCtrl.create({
message: data,
duration: 10000,
position: 'bottom'
});
toast.present();
});
【讨论】:
query 时打开/创建数据库?
在ionic-storage repo 上,他们说要使用Ionic Native SQLite plugin。 像这样:
import { SQLite } from 'ionic-native';
SQLite.openDatabase({
name: 'data.db',
location: 'default'
})
.then((db: SQLite) => {
db.executeSql('create table danceMoves(name VARCHAR(32))', {}).then(() => {}).catch(() => {});
})
.catch(error => console.error('Error opening database', error));
【讨论】: