7

I am using andpor/react-native-sqlite-storage for managing SQLite database in React native. Now I want to backup all my database into a encrypted file then restore this at later time. I know how to do this in android but don't know how to implement this in react native.

if it is in android below code can help me to backup the database without encryption.

 final String inFileName = "/data/data/<your.app.package>/databases/foo.db";
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);

String outFileName = Environment.getExternalStorageDirectory()+"/database_copy.db";

// Open the empty db as the output stream
OutputStream output = new FileOutputStream(outFileName);

// Transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer))>0){
    output.write(buffer, 0, length);
}

// Close the streams
output.flush();
output.close();
fis.close();

So my question is how I can do this on React Native. If there any libraries available please suggest to me.

0

2 Answers 2

4

Same approach can be followed in react-native too using react-native-fs package.

import RNFS from 'react-native-fs';

RNFS.readFile("/data/data/<your.app.package>/databases/foo.db", "base64")
    .then(value => RNFS
        .getAllExternalFilesDirs()
        .then(path => RNFS.writeFile(path + "/" + "database_copy.db", value, "base64"))
        .then(() => console.log("Successful"))
    )

Sign up to request clarification or add additional context in comments.

Comments

1

Here is what I did:

import DocPicker from 'react-native-document-picker'
import RNFS from 'react-native-fs'

async function restoreDB() {
    try {
        const rsPicker = await DocPicker.pickSingle()
        const filePath = rsPicker.uri
        await RNFS.copyFile(filePath, '/data/data/<your.app.package>/databases/foo.db')
        msgInfo('Success Restore Database');

    } catch (e) {
        msgError(e)
    }
}

async function backupDB() {
    try {
        const currDate = format(new Date(), 'dd_MM_yyyy_HHmmss')
        const destPath = RNFS.ExternalStorageDirectoryPath + 'foo_' + currDate + '.db'
        await RNFS.copyFile('/data/data/<your.app.package>/databases/foo.db',
            destPath)
        msgInfo('Success Backup Database');
    } catch (e) {
        msgError(e)
    }
}

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.