1 | initial version |
There are multiple ways to create a backup of data from a SQLite database in React Native for Android, but one possible method is as follows:
npm install --save react-native-sqlite-storage
import SQLite from 'react-native-sqlite-storage';
const db = SQLite.openDatabase({
name: 'mydb.db',
location: 'default',
});
db.transaction(function(txn) {
txn.executeSql(
'CREATE TABLE IF NOT EXISTS mytable (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, value REAL)'
);
});
function exportData() {
return new Promise((resolve, reject) => {
db.transaction(function(txn) {
txn.executeSql('SELECT * FROM mytable ORDER BY id ASC', [], function(
tx,
results
) {
const rows = results.rows.raw(); // Convert to plain JavaScript object
resolve(rows);
});
});
});
}
exportData()
function and save the result to a file using the following code:import { writeFile } from 'react-native-fs';
const data = await exportData();
const jsonString = JSON.stringify(data);
const filePath = '/sdcard/mybackup.json'; // Choose a location to save the file
await writeFile(filePath, jsonString, 'utf8');
Note: The writeFile()
function requires the react-native-fs
plugin to be installed and the app to have the necessary permissions to access the file system. Also, make sure to choose a secure location to save the backup file and protect it with encryption or other security measures if needed.