前言
对于存放数据量小且简易的数据我们可以通过AsyncStorage来存储,但对于数据结构复杂、数据量大的数据,我们可以使用移动开发中常用的sqlite来处理。
sqlite是一种轻型的数据库,多用于移动端开发,在原生应用开发中比较常见。
使用
React Native并没有提供使用sqlite的组件,我们可以通过使用第三方组件react-native-sqlite来使用原生的sqliteDatabase。
Android版配置
1. 安装
在项目根目录下执行cmd命令:
npm install --save react-native-sqlite-storage
2. 修改settings.gradle配置
修改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')
3. 修改build.gradle配置
修改android/app/build.gradle的配置
...
dependencies {
...
compile project(':react-native-sqlite-storage')
}
4. 在MainApplication.java注册模块
修改android/app/src/main/java/com/[YourAppName]/MainApplication.java的配置
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(),// register sqlite Plugin here
new MainReactPackage());
}
}
iOS版配置
1. 安装
在项目根目录下执行cmd命令:
npm install --save react-native-sqlite-storage
2. XCode sqlite项目依赖安装
将sqlite项目作为一个库进行依赖到当前项目,如下:
3.XCode sqlite库依赖
将libsqlite.a添加到Libraries and Frameworks中,同时添加sqlite3.0.tbd (XCode 7) 或者libsqlite3.0.dylib (XCode 6 and earlier)到当前位置:
使用实例
新建一个数据库的工具组件sqlite.js,该模块类似于工具类,用于数据库的建表、增删改查等操作,不需要渲染任何界面,所以render return null。
import React from 'react';
import sqliteStorage from 'react-native-sqlite-storage';
sqliteStorage.DEBUG(true);
sqliteStorage.DEBUG(true);
var database_name = "test.db";//数据库文件
var database_version = "1.0";//版本号
var database_displayname = "MysqLite";
var database_size = -1;
var db;
export default class sqlite extends Component {
render(){
return null;
}
}
创建数据表
这里创建了一个用户信息表,表结构如下:
字段 | 类型 | 描述 |
---|---|---|
id | INTEGER | 主键 |
name | VARCHAR | 姓名 |
age | VARCHAR | 年龄 |
sex | VARCHAR | 性别 |
phone | VARCHAR | 电话号码 |
VARCHAR | 邮箱 | |
address | VARCHAR | 地址 |
createTable(){
if (!db) {
this.open();
}
//创建用户表
db.transaction((tx)=> { tx.executesql('CREATE TABLE IF NOT EXISTS USER(' + 'id INTEGER PRIMARY KEY AUTOINCREMENT,' + 'name VARCHAR,'+ 'age VARCHAR,' + 'sex VARCHAR,' + 'phone VARCHAR,' + 'email VARCHAR,' + 'address VARCHAR)',[],()=> { this._successCB('executesql'); },(err)=> { this._errorCB('executesql',err); }); },(err)=> {//所有的 transaction都应该有错误的回调方法,在方法里面打印异常信息,不然你可能不会知道哪里出错了。 this._errorCB('transaction',err); },()=> { this._successCB('transaction'); }) }
open(){
db = sqliteStorage.openDatabase(
database_name,database_version,database_displayname,database_size,()=>{
this._successCB('open');
},(err)=>{
this._errorCB('open',err);
});
return db;
}
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);
}
插入数据
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,address],()=>{
},(err)=>{
console.log(err);
}
);
}
},(error)=>{
this._errorCB('transaction',error);
},()=>{
this._successCB('transaction insert data');
});
}
删除数据
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');
});
}
//sqlite.js
import React,{ Component } from 'react';
import {
ToastAndroid,} from 'react-native';
import sqliteStorage from 'react-native-sqlite-storage';
sqliteStorage.DEBUG(true);
var database_name = "test.db";//数据库文件
var database_version = "1.0";//版本号
var database_displayname = "MysqLite";
var database_size = -1;
var db;
export default class sqlite extends Component {
componentWillUnmount(){
if(db){
this._successCB('close');
db.close();
}else {
console.log("sqliteStorage not open");
}
}
open(){
db = sqliteStorage.openDatabase(
database_name,err);
});
return db;
}
createTable(){
if (!db) {
this.open();
}
//创建用户表
db.transaction((tx)=> {
tx.executesql('CREATE TABLE IF NOT EXISTS USER(' +
'id INTEGER PRIMARY KEY AUTOINCREMENT,' +
'name varchar,'+
'age VARCHAR,' +
'sex VARCHAR,' +
'phone VARCHAR,' +
'email VARCHAR,' +
'address VARCHAR)',()=> {
this._successCB('executesql');
},(err)=> {
this._errorCB('executesql',err);
});
},(err)=> {//所有的 transaction都应该有错误的回调方法,在方法里面打印异常信息,不然你可能不会知道哪里出错了。
this._errorCB('transaction',()=> {
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',()=>{
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,()=>{
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;
}
}
调用工具类
在同一目录下新建sqliteDemo.js调用sqlite.js中封装好的方法,注意使用时先引入sqlite.js
import React,{ Component } from 'react';
import {
AppRegistry,Text,View,} from 'react-native';
import sqlite from './sqlite';
var sqlite = new sqlite();
var db;
export default class sqliteDemo extends Component{
constructor(props) {
super(props);
this.state = {
name:"",age:"",phone:"",email:"",address:"",};
}
compennetDidUnmount(){
//关闭数据库
sqlite.close();
}
componentWillMount(){
//开启数据库
if(!db){
db = sqlite.open();
}
//建表
sqlite.createTable();
//删除数据
sqlite.deleteData();
//模拟数据
var userData = [];
var user = {};
user.name = "Mr.Onion";
user.age = "26";
user.sex = "男";
user.phone = "12345678910";
user.email = "123454321@qq.com";
user.address = "A市B街111号C室";
userData.push(user);
//插入数据
sqlite.insertUserData(userData);
//查询
db.transaction((tx)=>{
tx.executesql("select * from user",(tx,results)=>{
var len = results.rows.length;
for(let i=0; i<len; i++){
var u = results.rows.item(i);
this.setState({
name:u.name,age:u.age,phone:u.phone,email:u.email,address:u.address,});
}
});
},(error)=>{
console.log(error);
});
}
render(){
return (
<View> <Text> 姓名:{this.state.name} </Text> <Text> 年龄:{this.state.age} </Text> <Text> 电话:{this.state.phone} </Text> <Text> Email:{this.state.email} </Text> <Text> 地址:{this.state.address} </Text> </View> ); } }