RN常用组件之SQLite


react-native-sqlite-storage

做一款完整的APP,数据存储自然是少不了的。当数据结构比较简单的时候AsyncStorage的键值对存储完全够用,但是面对一些复杂的数据结构我们就需要使用更为完善的持久方案。sqlite作为跨平台存储的优秀分子,哪里都少不了他的身影。

react-native-sqlite-storage是目前github上start最多的sqlite组件,也比较好用,下面介绍一下它的配置和基本使用。

安装配置(for Android)

install

1
npm install --save react-native-sqlite-storage
// file: android/settings.gradle
...
include ':react-native-sqlite-storage'
project(':react-native-sqlite-storage').projectDir = new File(rootProject.projectDir,'../node_modules/react-native-sqlite-storage/src/android')

// file: android/app/build.gradle
...
dependencies {
    ...
    compile project(':react-native-sqlite-storage')
}

Register

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import org.pgsqlite.SQLitePluginPackage;

public class MainApplication extends Application implements ReactApplication {
......

/**
* A list of packages used by the app. If the app uses additional views
* or modules besides the default ones, add more packages here.
*/
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new SQLitePluginPackage(), // 在这里添加一行,别忘了import
new MainReactPackage());
}
}

经过上述步骤,组件就可以使用了。

具体使用方法

全局设置

通常要把他设为全局,这样在任何地方都可以操作数据库。设置方法如下:

//在index.js里添加
1
2
3
import SQLite from 'react-native-sqlite-storage';
SQLite.DEBUG(true);
SQLite.enablePromise(true);

打开/创建数据库

首先需要一个数据库。

1
2
3
//打开数据库
//location属性只对iOS有效,android是默认的
SQLite.openDatabase({name: 'my.db', location: 'default'}, successcb, errorcb);

更多参数请移步GitHub查看。

创建表

1
2
3
4
5
6
7
8
//操作API:transaction(func,[func=>(error){}],[func=>{}])
db.transaction(function(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS DemoTable (name, score)');
}, function(error) {//失败回调
console.log('Transaction ERROR: ' + error.message);
}, function() {//成功回调
console.log('Populated database OK');
});

插入数据

1
2
3
4
5
6
7
db.transaction(function(tx) {
tx.executeSql('INSERT INTO DemoTable VALUES (?,?)', ['Alice', 101]);
}, function(error) {//失败回调
console.log('Transaction ERROR: ' + error.message);
}, function() {//成功回调
console.log('Populated database OK');
});

剩下的改查就不写了,可以看出来,就是在transaction()中调用executeSql()执行sql就行了。

特殊

对于包含count()这类函数的语句,其结果处理要直接在executeSql()中标明。

1
2
3
4
5
6
7
db.transaction(function(tx) {
tx.executeSql('SELECT count(*) AS mycount FROM DemoTable', [], function(tx, rs) {
console.log('Record count (expected to be 2): ' + rs.rows.item(0).mycount);
}, function(tx, error) {
console.log('SELECT error: ' + error.message);
});
});

完整代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
/**
* 产品类别表dao
*/
import React, { Component } from 'react';
import {
ToastAndroid,
} from 'react-native';
import SQLiteStorage from 'react-native-sqlite-storage';
SQLiteStorage .DEBUG(true);

var database_name = "ITEM.db";//数据库文件
var database_version = "1.0";//版本号
var database_displayname = "ITEMSQLite";
var database_size = -1;
var db;

export default class TBaseSblbDao extends Component {
componentWillUnmount(){
if(db){
this._successCB('close');
db.close();
}else {
console.log("SQLiteStorage not open");
}
}
open(){
db = SQLiteStorage.openDatabase(
database_name,
database_version,
database_displayname,
database_size,
()=>{
this._successCB('open');
},
(err)=>{
this._errorCB('open',err);
});
return db;
}
createTable(){
if (!db) {
this.open();
}
//创建产品类别表
db.transaction((tx)=> {
tx.executeSql('CREATE TABLE IF NOT EXISTS T_BASE_SBLB(' +
'F_ID VARCHAR PRIMARY KEY AUTOINCREMENT,' +
'F_BM VARCHAR,'+
'F_FBM VARCHAR,' +
'F_MC VARCHAR,' +
'F_TYPE VARCHAR,' +
'F_YRJ VARCHAR,' +
'F_PX VARCHAR)'
, [], ()=> {
this._successCB('executeSql');
}, (err)=> {
this._errorCB('executeSql', err);
});
}, (err)=> {//所有的 transaction都应该有错误的回调方法
this._errorCB('transaction', err);
}, ()=> {
this._successCB('transaction');
})
}
deleteData(){//清空数据
if (!db) {
this.open();
}
db.transaction((tx)=>{
tx.executeSql('delete from user',[],()=>{

});
});
}
dropTable(){//删除表
db.transaction((tx)=>{
tx.executeSql('drop table user',[],()=>{

});
},(err)=>{
this._errorCB('transaction', err);
},()=>{
this._successCB('transaction');
});
}
insertUserData(userData){
let len = userData.length;
if (!db) {
this.open();
}
this.createTable();
this.deleteData();
db.transaction((tx)=>{
for(let i=0; i<len; i++){
//这部分是示例,照这个写就行,字段必须和传入的对应。
// var user = userData[i];
// let name= user.name;
// let age = user.age;
// let sex = user.sex;
// let phone = user.phone;
// let email = user.email;
// let address = user.address;
// let sql = "INSERT INTO user(name,age,sex,phone,email,address)"+
// "values(?,?,?,?,?,?)";
// tx.executeSql(sql,[name,age,sex,phone,email,address],()=>{

// },(err)=>{
// console.log(err);
// }
// );
}
},(error)=>{
this._errorCB('transaction', error);
},()=>{
this._successCB('transaction insert data');
});
}
close(){
if(db){
this._successCB('close');
db.close();
}else {
console.log("SQLiteStorage not open");
}
db = null;
}
_successCB(name){
console.log("SQLiteStorage "+name+" success");
}
_errorCB(name, err){
console.log("SQLiteStorage "+name);
console.log(err);
}

render(){
return null;
}
}

遇到的坑

如果直接使用db.transaction,请设置SQLite.enablePromise(false),否则会报transaction is not a function

全局设置时候global最好写成GLOBAL

-------------本文结束,感谢您的阅读-------------

本文标题:RN常用组件之SQLite

文章作者:饭饭君~

发布时间:2018年03月07日 - 08:41

最后更新:2019年04月23日 - 10:50

原始链接:https://yangcf.github.io/2018/03/07/RN常用组件之SQLite/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

如果我的文章有帮助到你,欢迎打赏~~
0%