[RN] React Native 使用 realm 数据库

 React Native 使用 realm  数据库

realm 是一款专为移动 ​ 端开发的高性能数据库,其宣称自己是最快的 react-native 数据库。
realm 整体的优点有这么四点:
1.简单易用,
2.跨平台,
3.快速性能优越,
4.提供高级功能。realm 核心数据引擎用 C++ 打造,并不是建立在 SQLite 之上的 ORM。因此性能就是比普通的 ORM 要快很多,甚至比单独无封装的 SQLite 还要快。同时因为是 ORM,本身在设计时也针对移动设备(iOS、Android),所以简单易用,学习成本很低。

一、安装依赖

npm i -S realm

Link

react-native link

 

二、使用

1)先定义工具文件

RealmUtil.js

import Realm from 'realm';

/***表定义区**/
export const HistoryTableName = 'History';
export const CityTableName = 'City';

const HistorySchema = {
    name: HistoryTableName,
    primaryKey: 'id',
    properties: {
        id: 'int',
        name: 'string',
    }
};


const CitySchema = {
    name: CityTableName,
    primaryKey: 'city_id',
    properties: {
        city_id: 'int',
        city_name: 'string',
    }
};

const instance = new Realm({
    schema: [
        HistorySchema,
        CitySchema,
    ],
    deleteRealmIfMigrationNeeded: true,
    inMemory: false,
});


/***表使用区**/
export function writeToRealm(obj,tabName) {
    return new Promise((resolve, reject) => {
        instance.write(() => {
            instance.create(tabName, obj, true)
            resolve(true)
        })
    })
}


export function queryAllFromRealm(tabName) {
    return new Promise((resolve, reject) => {
        let obj = instance.objects(tabName);
        let objStr = JSON.stringify(obj);
        resolve(JSON.parse(objStr))
    })
}

export function clearAllFromRealm(tabName) {
    return new Promise((resolve, reject) => {
        instance.write(() => {
            let arrays = instance.objects(tabName);
            instance.delete(arrays);
            resolve(true)
        })
    })
}


export function clearRowFromRealm(id,tabName) {
    return new Promise((resolve, reject) => {
        instance.write(() => {
            let arrays = instance.objects(tabName);
            let row = arrays.filtered('id==' + id);
            instance.delete(row);
            resolve(true)
        })
    })
}

 

2)调用文件

import React, {Component} from "react";
import {StyleSheet, Text, ToastAndroid, TouchableHighlight, View,} from 'react-native';
import {
    HistoryTableName,
    CityTableName,
    clearAllFromRealm,
    queryAllFromRealm,
    writeToRealm,
    clearRowFromRealm
} from "./RealmUtil";

export default class TestRealm extends Component {
    componentWillMount() {

    }

    //表1操作
    _addData() {
        clearAllFromRealm(HistoryTableName);

        let row1 = {"id": 1, "name": "战狼1"};
        writeToRealm(row1, HistoryTableName).then(() => {
            ToastAndroid.show('写入完成1', ToastAndroid.SHORT);
        });
        let row2 = {"id": 2, "name": "战狼2"};
        writeToRealm(row2, HistoryTableName).then(() => {
            ToastAndroid.show('写入完成2', ToastAndroid.SHORT);
        });
    }

    _readAllData() {
        queryAllFromRealm(HistoryTableName).then((list) => {
            for (let key in list) {
                ToastAndroid.show('id:' + list[key].id + ',name:' + list[key].name, ToastAndroid.SHORT);
            }
        });
    }

    _updateData() {
        let row2 = {"id": 2, "name": "北京222"};
        writeToRealm(row2, HistoryTableName).then(() => {
            ToastAndroid.show('修改完成', ToastAndroid.SHORT);
        });
    }

    _delRowData() {
        //删除第一行
        clearRowFromRealm(1, HistoryTableName).then(() => {
            ToastAndroid.show('删除完成', ToastAndroid.SHORT);
        });
    }

    //表2操作
    _addData2() {
        clearAllFromRealm(CityTableName);

        let row1 = {"city_id": 1, "city_name": "上海"};
        writeToRealm(row1, CityTableName).then(() => {
            ToastAndroid.show('2写入完成1', ToastAndroid.SHORT);
        });
        let row2 = {"city_id": 2, "city_name": "北京"};
        writeToRealm(row2, CityTableName).then(() => {
            ToastAndroid.show('2写入完成2', ToastAndroid.SHORT);
        });
    }

    _readAllData2() {
        queryAllFromRealm(CityTableName).then((list) => {
            for (let key in list) {
                ToastAndroid.show('城市ID:' + list[key].city_id + ',城市名:' + list[key].city_name, ToastAndroid.SHORT);
            }
        });
    }

    render() {
        return (
            <View style={{flex: 1}}>
                <View style={{padding: 10}}><Text>表1操作</Text></View>
                <TouchableHighlight onPress={() => this._delRowData()} style={styles.button} underlayColor="#a5a5a5">
                    <Text>删除第一行</Text>
                </TouchableHighlight>
                <TouchableHighlight onPress={() => this._addData()} style={styles.button} underlayColor="#a5a5a5">
                    <Text>增加数据</Text>
                </TouchableHighlight>
                <TouchableHighlight onPress={() => this._updateData()} style={styles.button} underlayColor="#a5a5a5">
                    <Text>修改数据</Text>
                </TouchableHighlight>
                <TouchableHighlight onPress={() => this._readAllData()} style={styles.button} underlayColor="#a5a5a5">
                    <Text>读取全部数据</Text>
                </TouchableHighlight>

                <View style={{padding: 10, marginTop: 10}}><Text>表2操作</Text></View>
                <TouchableHighlight onPress={() => this._addData2()} style={styles.button} underlayColor="#a5a5a5">
                    <Text>增加数据</Text>
                </TouchableHighlight>
                <TouchableHighlight onPress={() => this._readAllData2()} style={styles.button} underlayColor="#a5a5a5">
                    <Text>读取全部数据</Text>
                </TouchableHighlight>
            </View>
        );

    }
}

const styles = StyleSheet.create({
    button: {
        margin: 3,
        backgroundColor: 'white',
        padding: 10,
        borderBottomWidth: StyleSheet.hairlineWidth,
        borderBottomColor: '#cdcdcd'
    },
});

 

 

三、如何查看数据文件

笔者是在Genymotion模拟器里测试的

思路是使用 adb 命令 ,先 复制到本地 windows 下,然后用 Realm Studio 打开 realm 文件即可!

复制步骤如下:

1)先连接远程

adb remount

2)查看对应目录下文件

adb ls /data/data/com.testdemo/files

看到结果如下:

000041f9 00001000 5cece0e8 .
000041e9 00001000 5cece048 ..
000041c0 00001000 5cece0e8 default.realm.management
00008180 00316390 5cece0e7 ReactNativeDevBundle.js
00008180 00000498 5cece0fe default.realm.lock
00008180 00004000 5cece0fc default.realm
00001180 00000000 5cece0fc default.realm.note

3)对,没错,然后复制  default.realm  出来就行

adb pull /data/data/com.testdemo/files/default.realm  d:/m

注意: com.testdemo   为自己的包名,要对应的修改 。 最后的 d:/m  为 自己要复制的win目录。

 

本博客地址: wukong1688

本文原文地址:https://www.cnblogs.com/wukong1688/p/10935043.html

转载请著名出处!谢谢~~

 

今日心得:

苦难

 

posted @ 2019-05-28 08:41  wukong1688  阅读(3030)  评论(0编辑  收藏  举报