Expo SQLite (legacy)
A library that provides access to a database that can be queried through a WebSQL-like API.
expo-sqlite
gives your app access to a database that can be queried through a WebSQL-like API. The database is persisted across restarts of your app.
Installation
-
npx expo install expo-sqlite
If you are installing this in an existing React Native app, make sure to install expo
in your project.
Usage
An example to-do list app is available that uses this module for storage.
Importing an existing database
To open a new SQLite database using an existing .db
file you already have, follow the steps below:
1
Install expo-file-system
and expo-asset
modules:
-
npx expo install expo-file-system expo-asset
2
Create a metro.config.js file at the root of your project with the following contents to include extra asset extensions:
const { getDefaultConfig } = require('expo/metro-config');
const defaultConfig = getDefaultConfig(__dirname);
defaultConfig.resolver.assetExts.push('db');
module.exports = defaultConfig;
3
Use the following function (or similar) to open your database:
import * as FileSystem from 'expo-file-system';
import * as SQLite from 'expo-sqlite/legacy';
import { Asset } from 'expo-asset';
async function openDatabase(pathToDatabaseFile: string): Promise<SQLite.SQLiteDatabase> {
if (!(await FileSystem.getInfoAsync(FileSystem.documentDirectory + 'SQLite')).exists) {
await FileSystem.makeDirectoryAsync(FileSystem.documentDirectory + 'SQLite');
}
const asset = await Asset.fromModule(require(pathToDatabaseFile)).downloadAsync();
await FileSystem.copyAsync({
from: asset.localUri,
to: FileSystem.documentDirectory + 'SQLite/myDatabaseName.db',
});
return SQLite.openDatabase('myDatabaseName.db');
}
Executing statements with an async transaction
import * as SQLite from 'expo-sqlite/legacy';
const db = SQLite.openDatabase('dbName', version);
const readOnly = true;
await db.transactionAsync(async tx => {
const result = await tx.executeSqlAsync('SELECT COUNT(*) FROM USERS', []);
console.log('Count:', result.rows[0]['COUNT(*)']);
}, readOnly);
Executing statements outside of a transaction
You should use this kind of execution only when it is necessary. For instance, when code is a no-op within transactions. Example:
PRAGMA foreign_keys = ON;
.
import * as SQLite from 'expo-sqlite/legacy';
const db = SQLite.openDatabase('dbName', version);
await db.execAsync([{ sql: 'PRAGMA foreign_keys = ON;', args: [] }], false);
console.log('Foreign keys turned on');
API
import * as SQLite from 'expo-sqlite/legacy';
No API data file found, sorry!