美文网首页
React native 数据存储

React native 数据存储

作者: abu2013 | 来源:发表于2019-01-21 15:43 被阅读0次

SQlite3

1,使用

React Native并没有提供使用sqlite的组件,我们可以通过使用第三方组件react-native-sqlite来使用原生的SQLiteDatabase。

2,安装

在项目根目录下执行cmd命令:

yard install --save react-native-sqlite-storage
yard install react-native-store

nmp install --save react-native-sqlite-storage
nmp install react-native-store

3,XCode SQLite项目依赖安装

pod 'react-native-sqlite-storage', :path => '../node_modules/react-native-sqlite-storage'

然后

pod install

将SQLite项目作为一个库进行依赖到当前项目,如下:


4.XCode SQLite库依赖

5,使用实例

新建一个数据库的工具组件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 电话号码
email 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和关闭数据库close的方法

 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,age,sex,phone,email,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的完整代码如下:

//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,
            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 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');
        })
    }
    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;
    }
}

调用工具类
在同一目录下新建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>
        );
    }
}

相关文章

网友评论

      本文标题:React native 数据存储

      本文链接:https://www.haomeiwen.com/subject/dqvcjqtx.html