我一直在浏览一篇又一篇“不是我正在寻找的”答案的文章。我找到了一个法语视频。这里是:Ionic 3 Store Data
话虽如此,这里是如何设置您的代码以使 ionic 3 cordova sqlite 可用。
1) 通过在 npm 或 cmd 提示符下运行这 2 个命令来导入您的原生 sqlite。
ionic cordova plugin add cordova-sqlite-storage
npm install --save @ionic-native/sqlite
2) 导入你的 app.module.ts
import { SQLite} from '@ionic-native/sqlite';
3) 在你的 app.module.ts 中添加为提供者
providers: [
...
SQLite,
...
]
4) 创建一个新文件夹(如果你想让它成为一个不同的组件)并制作一个数据库 ts 文件。为了方便起见,我调用了我的 database.ts
5) 添加以下代码(请注意,这不是我使用的真实代码。只是一个示例。用户名和密码不应以这种方式存储):
import { Injectable } from '@angular/core';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';
@Injectable()
export class Database {
theConsole: string = "Console Messages";
options: any = {
name: data.db,
location: 'default',
createFromLocation: 1
}
private db: SQLiteObject;
constructor(private sqlite: SQLite) {
this.connectToDb();
}
private connectToDb():void {
this.sqlite.create(this.options)
.then((db: SQLiteObject) => {
this.db = db;
var sql = 'create table IF NOT EXISTS `user` (username VARCHAR(255), password VARCHAR(255))';
//IF you move the below statment out of here then the db variable will not be initialized
//before you can use it to execute the SQL.
this.db.executeSql(sql, {})
.then(() => this.theConsole += 'Executed SQL' + sql)
.catch(e => this.theConsole += "Error: " + JSON.stringify(e));
})
.catch(e => this.theConsole += JSON.stringify(e));
}
addUser(username, password):void {
var sql = "INSERT INTO `user` (username,password) VALUES ('"+username+"','"+ password+"')";
this.db.executeSql(sql,{})
.then(() => this.theConsole += "\n" + 'Executed SQL' + sql)
.catch(e => this.theConsole += "Error: " + JSON.stringify(e));
}
getDealer() {
var sql = "SELECT * FROM user";
this.db.executeSql(sql, {})
.then((result) => {
this.theConsole += JSON.stringify(result);
if (result.rows.length > 0) {
this.theConsole += 'Result' + result.rows.item(0);
}
this.theConsole += "\n" + result.rows.item(0).username+ result.rows.item(0).password;
this.theConsole += "\n" +'Rows' + result.rows.length;
})
.catch(e => this.theConsole += JSON.stringify(e));
}
getConsoleMessages() {
return this.theConsole;
}
}
然后,您只需将数据库组件(类)导入您的一个页面,您就可以通过运行这些函数或创建您自己的 RunSQL 函数来访问数据库,您可以将任何您想要的东西放入其中。
真正让我在 ionic 的网站上感到困惑的部分是,他们展示的是 SQLiteObject 的创建而不是重用。
通过添加:
private db: SQLiteObject;
在类变量的声明和db对象的初始化中我的代码:
...
this.sqlite.create(this.options)
.then((db: SQLiteObject) => {
this.db = db;
...
我能够重复使用 db 变量,而不必一遍又一遍地打开 db 连接。
6) 将组件类导入页面
import { Database } from '../../data/database';
我使用这个网站:ionic native sqlite 主要了解如何设置它以及前面提到的法语视频。我希望我会发现我希望可以帮助其他人碰到同样的 sqlite 墙。我希望我能早点找到我今天发现的东西。我希望可以帮助其他人碰到同样的 sqlite 墙。