There are many ways to store databases for mobile. I have the rules when choosing a mobile DB: Lightweight, Low memory, Fast, secure, and easy to use. I have used a few databases for mobile, in conclusion, I refer to using SQLite or Realm.
Both these databases are relational databases and designed for mobile.
If your application needs a simple database, SQLite is a good choice, it also supports transactions besides CRUD basic.
// SQL Lite
function getSettings(callBack) {
db.transaction(function (txn) {
txn.executeSql(
'SELECT * FROM Settings',
[],
function (tx, res) {
let settings = {};
if (res.rows.length > 0) {
const len = res.rows.length;
for (let i = 0; i < len; i++) {
const row = res.rows.item(i);
if (row.datatype === 'bool') {
settings[row.code] = row.value === 'true';
} else {
settings[row.code] = row.value;
}
}
}
callBack(settings);
},
handleErrorCB,
);
});
}
// Realm
async function getSetting(): Promise<SettingModel> {
const settings = realm.objects<SettingModel>(TABLE_NAME);
if (settings.length === 0) {
return getDefaultSetting();
}
return createSettingFromData(settings[0]);
}
async function saveSetting(settingInput: SettingModel): Promise<SettingModel> {
if (settingInput.id === '') {
settingInput.id = Guid.create().toString();
}
const settings = realm.objects<SettingModel>(TABLE_NAME);
let setting: SettingModel;
if (settings.length > 0) {
setting = settings[0];
}
const result = realm.write(() => {
if (!setting) {
return realm.create(TABLE_NAME, settingInput, Realm.UpdateMode.Modified);
} else {
setting.companyName = settingInput.companyName;
setting.taxPercent = settingInput.taxPercent;
setting.isIncludeTax = settingInput.isIncludeTax;
setting.phone = settingInput.phone;
setting.address = settingInput.address;
setting.currency = settingInput.currency;
setting.language = settingInput.language;
return setting;
}
});
return createSettingFromData(result);
}
But Real files can not open concurrently by multiple threads, it is inconvenient in some cases. RealmObject is live objects, some time got issues when modifying objects.