react-native 海量本地存储数据使用 react-native-sqlite-storage

谷梁鸣
2023-12-01

在开发app涉及到聊天功能,聊天数据的存储就成了不可避免的问题。此时就需要使用 react-native-sqlite-storage 来解决这个问题。

1、环境

react-native 版本0.61、node.js版本12.15.0

2、安装

npm install --save react-native-sqlite-storage

react-native0.61版本默认link,是不需要手动link的

3、android配置

①配置 项目名称/android/app/build.gradle 文件

// 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')

暂时未用到其他配置

4、ios配置  (暂时未测试)

5、使用方式

import React from 'react';
import {
    ToastAndroid,
} from 'react-native';
import SQLiteStorage from 'react-native-sqlite-storage';
SQLiteStorage.DEBUG(true);
let database_name = "msg.db";//数据库文件
let database_version = "1.0";//版本号
let database_displayname = "MySQLite";
let database_size = -1;//-1应该是表示无限制
let db;
export default class SQLite extends React.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,' +//表id
                'useruuid VARCHAR,' +//用户uuid
                'unreadNum INTEGER,' +//未读数量
                'online INTEGER,' +//是否在线
                'relation VARCHAR,' +//关系类型 friend strange me system
                'url VARCHAR,' +//头像
                'name VARCHAR,' +//名称
                'nickname VARCHAR,' +//昵称
                'sex INTEGER,' +//性别
                'age INTEGER,' +//年龄
                'remark VARCHAR,' +//备注
                'telephone VARCHAR,' +//电话
                'platform VARCHAR,' +//平台
                'style VARCHAR,' +//样式
                'recordtime INTEGER)' //刷新时间
                , [], () => {
                    this._successCB('executeSql', '创建关系用户表成功!');
                }, (err) => {
                    this._errorCB('executeSql', err, '创建关系用户表失败!');
                });
        }, (err) => {//所有的 transaction都应该有错误的回调方法,在方法里面打印异常信息,不然你可能不会知道哪里出错了。
            this._errorCB('transaction', err);
        }, () => {
            this._successCB('transaction');
        })
        //创建聊天信息表
        db.transaction((tx) => {
            tx.executeSql('CREATE TABLE IF NOT EXISTS msg(' +
                'id INTEGER PRIMARY KEY  AUTOINCREMENT,' +//msg表id
                'messageid INTEGER,' +//消息id
                'isread INTEGER,' +//消息id
                'classify VARCHAR,' +//消息实体类型
                'content VARCHAR,' +//消息内容
                'recordtime INTEGER,' +//消息时间
                'senderuuid VARCHAR,' +//发送者uuid
                'receiver VARCHAR,' +//接收者uuid
                'format 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();
        db.transaction((tx) => {
            for (let i = 0; i < len; i++) {
                let user = userData[i];
                let useruuid = user.useruuid;
                let unreadNum = user.unreadNum || 0;
                let online = user.online || 0;
                let relation = user.relation || 'me';
                let url = user.url || '';
                let name = user.name || '';
                let sex = user.sex || 0;
                let age = user.age || 0;
                let nickname = user.nickname || '';
                let telephone = user.telephone || '';
                let platform = user.platform || 'android';
                let style = user.style || '';
                let recordtime = user.recordtime || (new Date().getTime());
                let sql = "INSERT INTO user(useruuid,unreadNum,online,relation,url,name,nickname,telephone,platform,style,recordtime,sex,age)" +
                    "values(?,?,?,?,?,?,?,?,?,?,?,?,?)";
                tx.executeSql(sql, [useruuid, unreadNum, online, relation, url, name, nickname, telephone, platform, style, recordtime, sex, age], () => {
                    console.log("插入数据成功");
                }, (err) => {
                    console.log('插入数据', err);
                }
                );
            }
        }, (error) => {
            this._errorCB('transaction', error);
            ToastAndroid.show("数据插入失败", ToastAndroid.SHORT);
        }, () => {
            this._successCB('transaction insert data');
            ToastAndroid.show("成功插入 " + len + " 条用户数据", ToastAndroid.SHORT);
        });
    }
    insertMsgData(msgData) {
        let len = msgData.length;
        if (!db) {
            this.open();
        }
        this.createTable();
        console.log(len);

        db.transaction((tx) => {
            for (let i = 0; i < len; i++) {
                let msg = msgData[i];
                let messageid = msg.messageid;
                let isread = msg.isread || 0;
                let classify = msg.classify || 0;
                let content = msg.content || 'me';
                let senderuuid = msg.senderuuid || '';
                let receiver = msg.receiver || '';
                let format = msg.format || '';
                let recordtime = msg.recordtime || (new Date().getTime());
                let sql = "INSERT INTO msg(messageid,isread,classify,content,recordtime,senderuuid,receiver,format)" +
                    "values(?,?,?,?,?,?,?,?)";
                tx.executeSql(sql, [messageid, isread, classify, content, recordtime, senderuuid, receiver, format], () => {
                    console.log("插入数据成功");
                }, (err) => {
                    console.log('插入数据', err);
                }
                );
            }
        }, (error) => {
            this._errorCB('transaction', error);
            ToastAndroid.show("数据插入失败", ToastAndroid.SHORT);
        }, () => {
            this._successCB('transaction insert data');
            ToastAndroid.show("成功插入 " + len + " 条信息数据", ToastAndroid.SHORT);
        });
    }
    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((tx)=>{})表示提交事务

tx.executeSql('sql执行语句', [], () => {});  表示执行sql

具体sql执行语句规范可以参考 菜鸟教程

 类似资料: