做一款完整的APP,数据存储自然是少不了的。当数据结构比较简单的时候AsyncStorage的键值对存储完全够用,但是面对一些复杂的数据结构我们就需要使用更为完善的持久方案。sqlite作为跨平台存储的优秀分子,哪里都少不了他的身影。
react-native-sqlite-storage是目前github上start最多的sqlite组件,也比较好用,下面介绍一下它的配置和基本使用。
安装配置(for Android)
install
1 | npm install --save react-native-sqlite-storage |
link
// 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 | import org.pgsqlite.SQLitePluginPackage; |
经过上述步骤,组件就可以使用了。
具体使用方法
全局设置
通常要把他设为全局,这样在任何地方都可以操作数据库。设置方法如下:
//在index.js里添加
1 | import SQLite from 'react-native-sqlite-storage'; |
打开/创建数据库
首先需要一个数据库。1
2
3//打开数据库
//location属性只对iOS有效,android是默认的
SQLite.openDatabase({name: 'my.db', location: 'default'}, successcb, errorcb);
更多参数请移步GitHub查看。
创建表
1 | //操作API:transaction(func,[func=>(error){}],[func=>{}]) |
插入数据
1 | db.transaction(function(tx) { |
剩下的改查就不写了,可以看出来,就是在transaction()中调用executeSql()执行sql就行了。
特殊
对于包含count()这类函数的语句,其结果处理要直接在executeSql()中标明。1
2
3
4
5
6
7db.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 | /** |