This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.
Expo SQLite
A library that provides access to a database that can be queried through a SQLite API.
expo-sqlite gives your app access to a database that can be queried through a SQLite API. The database is persisted across restarts of your app.
On Apple TV, the underlying database file is in the caches directory and not the application documents directory, per Apple platform guidelines.
Installation
If you are installing this in an existing React Native app, make sure to install expo in your project.
Configuration in app config
You can configure expo-sqlite for advanced configurations using its built-in config plugin if you use config plugins in your project (Continuous Native Generation (CNG)). The plugin allows you to configure various properties that cannot be set at runtime and require building a new app binary to take effect. If your app does not use CNG, then you'll need to manually configure the library.
Example app.json with config plugin
Configurable properties
Web setup
Web support is in alpha and may be unstable. Create an issue on GitHub if you encounter any issues.
To use expo-sqlite on web, you need to configure Metro bundler to support wasm files and add HTTP headers to allow SharedArrayBuffer usage.
Add the following configuration to your metro.config.js. If you don't have the metro.config.js yet, you can run npx expo customize metro.config.js. Learn more.
If you deploy your app to web hosting services, you will also need to add the Cross-Origin-Embedder-Policy and Cross-Origin-Opener-Policy headers to your web server. Learn more about the COEP, COOP headers, and SharedArrayBuffer.
If you deploy your app on EAS Hosting, you can configure the headers in your app config:
Usage
Import the module from expo-sqlite.
Basic CRUD operations
Prepared statements
Prepared statements allow you to compile your SQL query once and execute it multiple times with different parameters. They automatically escape input parameters to defend against SQL injection attacks, and are recommended for queries that include user input. You can get a prepared statement by calling prepareAsync() or prepareSync() method on a database instance. The prepared statement can fulfill CRUD operations by calling executeAsync() or executeSync() method.
Note: Remember to call
finalizeAsync()orfinalizeSync()method to release the prepared statement after you finish using the statement.try-finallyblock is recommended to ensure the prepared statement is finalized.
Tagged template literals API
For convenience and improved developer experience, expo-sqlite provides Bun-inspired tagged template literals API through the db.sql property. This API automatically escapes parameters to prevent SQL injection attacks and provides automatic type inference based on the query type.
useSQLiteContext() hook
useSQLiteContext() hook with React.Suspense
As with the useSQLiteContext() hook, you can also integrate the SQLiteProvider with React.Suspense to show a fallback component until the database is ready. To enable the integration, pass the useSuspense prop to the SQLiteProvider component.
Executing queries within an async transaction
Due to the nature of async/await, any query that runs while the transaction is active will be included in the transaction. This includes query statements that are outside of the scope function passed to withTransactionAsync() and may be surprising behavior. For example, the following test case runs queries inside and outside of a scope function passed to withTransactionAsync(). However, all of the queries will run within the actual SQL transaction because the second UPDATE query runs before the transaction finishes.
Promise.all([ // 1. A new transaction begins db.withTransactionAsync(async () => { // 2. The value "first" is inserted into the test table and we wait 2 // seconds await db.execAsync('INSERT INTO test (data) VALUES ("first")'); await sleep(2000); // 4. Two seconds in, we read the latest data from the table const row = await db.getFirstAsync<{ data: string }>('SELECT data FROM test'); // ❌ The data in the table will be "second" and this expectation will fail. // Additionally, this expectation will throw an error and roll back the // transaction, including the `UPDATE` query below since it ran within // the transaction. expect(row.data).toBe('first'); }), // 3. One second in, the data in the test table is updated to be "second". // This `UPDATE` query runs in the transaction even though its code is // outside of it because the transaction happens to be active at the time // this query runs. sleep(1000).then(async () => db.execAsync('UPDATE test SET data = "second"')), ]);
The withExclusiveTransactionAsync() function addresses this. Only queries that run within the scope function passed to withExclusiveTransactionAsync() will run within the actual SQL transaction.
Executing PRAGMA queries
Tip: Enable WAL journal mode when you create a new database to improve performance in general.
Import an existing database
To open a new SQLite database using an existing .db file you already have, you can use the SQLiteProvider with assetSource.
Sharing a database between apps/extensions (iOS)
To share a database with other apps/extensions in the same App Group, you can use shared containers by following the steps below:
1
Configure the App Group in app config:
2
Use Paths.appleSharedContainers from the expo-file-system library to retrieve the path to the shared container:
Passing binary data
Use Uint8Array to pass binary data to the database:
Browse an on-device database
The expo-sqlite library includes a built-in DevTools inspector plugin that is automatically enabled in development and requires no extra setup. It lets you browse tables, view and edit rows, run SQL queries, and export databases directly from your browser. To open it, press Shift + M in the Expo CLI terminal to open the dev tools menu, and then select Open expo-sqlite to launch the inspector.
Alternatively, you can also use the drizzle-studio-expo dev tools plugin to launch Drizzle Studio, connected to a database in your app, directly from Expo CLI. This plugin can be used with any expo-sqlite configuration and does not require Drizzle ORM. Learn how to install and use the plugin.
Key-value storage
The expo-sqlite library provides Storage as a drop-in replacement for the @react-native-async-storage/async-storage library. This key-value store is backed by SQLite. If your project already uses expo-sqlite, you can leverage expo-sqlite/kv-store without needing to add another dependency.
Storage provides the same API as @react-native-async-storage/async-storage:
A key benefit of using expo-sqlite/kv-store is the addition of synchronous APIs for added convenience:
If you're currently using @react-native-async-storage/async-storage in your project, switching to expo-sqlite/kv-store is as simple as changing the import statement:
- import AsyncStorage from '@react-native-async-storage/async-storage'; + import AsyncStorage from 'expo-sqlite/kv-store';
The localStorage API
The expo-sqlite/localStorage/install module provides a drop-in implementation for the localStorage API. If you're already familiar with this API from the web, or you would like to be able to share storage code between web and other platforms, this may be useful. To use it, you just need to import the expo-sqlite/localStorage/install module:
Note:
import 'expo-sqlite/localStorage/install';is a no-op on web and will be excluded from the production JS bundle.
Security
SQL injections are a class of vulnerabilities where attackers trick your app into executing user input as SQL code. You must escape all user input passed to SQLite to defend against SQL injections. Prepared statements are an effective defense against this problem. They explicitly separate a SQL query's logic from its input parameters, and SQLite automatically escapes inputs when executing prepared statements.
Third-party library integrations
The expo-sqlite library is designed to be a solid SQLite foundation. It enables broader integrations with third-party libraries for more advanced higher-level features. Here are some of the libraries that you can use with expo-sqlite.
Drizzle ORM
Drizzle is a "headless TypeScript ORM with a head". It runs on Node.js, Bun, Deno, and React Native. It also has a CLI companion called drizzle-kit for generating SQL migrations.
Check out the Drizzle ORM documentation and the expo-sqlite integration guide for more details.
Knex.js
Knex.js is a SQL query builder that is "flexible, portable, and fun to use!"
Check out the expo-sqlite integration guide for more details.
SQLCipher
Note: SQLCipher is not supported on Expo Go.
SQLCipher is a fork of SQLite that adds encryption and authentication to the database. The expo-sqlite library supports SQLCipher for Android, iOS, and macOS. To use SQLCipher, you need to add the useSQLCipher config to your app.json as shown in the Configuration in app config section and run npx expo prebuild.
Right after you open a database, you need to set a password for the database using the PRAGMA key = 'password' statement.
API
Cheatsheet for the common API
The following table summarizes the common API for SQLiteDatabase and SQLiteStatement classes:
Component
Type: React.Element<NamedExoticComponent<SQLiteProviderProps>>
Context.Provider component that provides a SQLite database to all children.
All descendants of this component will be able to access the database using the useSQLiteContext hook.
SQLiteProviderAssetSourceImport a bundled database file from the specified asset module.
Example
assetSource={{ assetId: require('./assets/db.db') }}
string • Default: defaultDatabaseDirectoryThe directory where the database file is located.
(error: Error) => void • Default: rethrow the errorHandle errors from SQLiteProvider.
(db: SQLiteDatabase) => Promise<void>A custom initialization handler to run before rendering the children. You can use this to run database migrations or other setup tasks.
boolean • Default: falseEnable React.Suspense integration.
Example
export default function App() { return ( <Suspense fallback={<Text>Loading...</Text>}> <SQLiteProvider databaseName="test.db" useSuspense={true}> <Main /> </SQLiteProvider> </Suspense> ); }
Constants
Type: SQLiteStorage
This default instance of the SQLiteStorage class is used as a drop-in replacement for the AsyncStorage module from @react-native-async-storage/async-storage.
Type: Record<string, {
entryPoint: string,
libPath: string
} | undefined>
The pre-bundled SQLite extensions.
Type: any
The default directory for SQLite databases.
Type: SQLiteStorage
Alias for AsyncStorage, given the storage not only offers asynchronous methods.
Hooks
A global hook for accessing the SQLite database across components.
This hook should only be used within a <SQLiteProvider> component.
SQLiteDatabaseExample
export default function App() { return ( <SQLiteProvider databaseName="test.db"> <Main /> </SQLiteProvider> ); } export function Main() { const db = useSQLiteContext(); console.log('sqlite version', db.getFirstSync('SELECT sqlite_version()')); return <View /> }
Classes
A SQLite database.
SQLiteDatabase Properties
NativeDatabaseSQLiteOpenOptionsSQLiteDatabase Methods
Close the database.
Promise<void>Create a new session for the database.
Note: Running heavy tasks with this function can block the JavaScript thread and affect performance.
SQLiteSessionExecute all SQL queries in the supplied string.
Note: The queries are not escaped for you! Be careful when constructing your queries.
Promise<void>Execute all SQL queries in the supplied string.
Note: The queries are not escaped for you! Be careful when constructing your queries.
Note: Running heavy tasks with this function can block the JavaScript thread and affect performance.
voidA convenience wrapper around SQLiteDatabase.prepareAsync(), SQLiteStatement.executeAsync(), SQLiteExecuteAsyncResult.getAllAsync(), and SQLiteStatement.finalizeAsync().
Promise<T[]>Example
// For unnamed parameters, you pass values in an array. db.getAllAsync('SELECT * FROM test WHERE intValue = ? AND name = ?', [1, 'Hello']); // For unnamed parameters, you pass values in variadic arguments. db.getAllAsync('SELECT * FROM test WHERE intValue = ? AND name = ?', 1, 'Hello'); // For named parameters, you should pass values in object. db.getAllAsync('SELECT * FROM test WHERE intValue = $intValue AND name = $name', { $intValue: 1, $name: 'Hello' });
A convenience wrapper around SQLiteDatabase.prepareSync(), SQLiteStatement.executeSync(), SQLiteExecuteSyncResult.getAllSync(), and SQLiteStatement.finalizeSync().
Note: Running heavy tasks with this function can block the JavaScript thread and affect performance.
T[]A convenience wrapper around SQLiteDatabase.prepareAsync(), SQLiteStatement.executeAsync(), SQLiteExecuteAsyncResult AsyncIterator, and SQLiteStatement.finalizeAsync().
AsyncIterableIterator<T>Rather than returning Promise, this function returns an AsyncIterableIterator. You can use for await...of to iterate over the rows from the SQLite query result.
A convenience wrapper around SQLiteDatabase.prepareSync(), SQLiteStatement.executeSync(), SQLiteExecuteSyncResult Iterator, and SQLiteStatement.finalizeSync().
Note: Running heavy tasks with this function can block the JavaScript thread and affect performance.
IterableIterator<T>This function returns an IterableIterator. You can use for...of to iterate over the rows from the SQLite query result.
A convenience wrapper around SQLiteDatabase.prepareAsync(), SQLiteStatement.executeAsync(), SQLiteExecuteAsyncResult.getFirstAsync(), and SQLiteStatement.finalizeAsync().
Promise<T | null>A convenience wrapper around SQLiteDatabase.prepareSync(), SQLiteStatement.executeSync(), SQLiteExecuteSyncResult.getFirstSync(), and SQLiteStatement.finalizeSync().
Note: Running heavy tasks with this function can block the JavaScript thread and affect performance.
T | nullAsynchronous call to return whether the database is currently in a transaction.
Promise<boolean>Synchronous call to return whether the database is currently in a transaction.
booleanLoad a SQLite extension.
Promise<void>Example
// Load `sqlite-vec` from `bundledExtensions`. You need to enable `withSQLiteVecExtension` to include `sqlite-vec`. const extension = SQLite.bundledExtensions['sqlite-vec']; await db.loadExtensionAsync(extension.libPath, extension.entryPoint); // You can also load a custom extension. await db.loadExtensionAsync('/path/to/extension');
Load a SQLite extension.
voidExample
// Load `sqlite-vec` from `bundledExtensions`. You need to enable `withSQLiteVecExtension` to include `sqlite-vec`. const extension = SQLite.bundledExtensions['sqlite-vec']; db.loadExtensionSync(extension.libPath, extension.entryPoint); // You can also load a custom extension. db.loadExtensionSync('/path/to/extension');
Create a prepared SQLite statement.
Note: Running heavy tasks with this function can block the JavaScript thread and affect performance.
SQLiteStatementA convenience wrapper around SQLiteDatabase.prepareAsync(), SQLiteStatement.executeAsync(), and SQLiteStatement.finalizeAsync().
Promise<SQLiteRunResult>A convenience wrapper around SQLiteDatabase.prepareSync(), SQLiteStatement.executeSync(), and SQLiteStatement.finalizeSync().
Note: Running heavy tasks with this function can block the JavaScript thread and affect performance.
SQLiteRunResultSerialize the database as Uint8Array.
Note: Running heavy tasks with this function can block the JavaScript thread and affect performance.
Uint8ArrayExecute SQL queries using tagged template literals (Bun-style API). Queries are automatically protected against SQL injection using prepared statements.
The query result is directly awaitable and returns an array of objects by default.
Use .values(), .first(), or .each() for different result formats.
SQLiteTaggedQuery<T>Example
// Direct await - returns array of objects const users = await sql<User>`SELECT * FROM users WHERE age > ${21}`; // Get first row only const user = await sql<User>`SELECT * FROM users WHERE id = ${userId}`.first(); // Get values as arrays const rows = await sql`SELECT name, age FROM users`.values(); // Returns: [["Alice", 30], ["Bob", 25]] // INSERT/UPDATE/DELETE - returns SQLiteRunResult const result = await sql`INSERT INTO users (name, age) VALUES (${name}, ${age})` as SQLiteRunResult; console.log('Inserted row:', result.lastInsertRowId); // Iteration for await (const user of db<User>`SELECT * FROM users`.each()) { console.log(user.name); } // Synchronous API const users = sql<User>`SELECT * FROM users WHERE age > ${21}`.allSync(); const user = sql<User>`SELECT * FROM users WHERE id = ${userId}`.firstSync();
Synchronize the local database with the remote libSQL server. This method is only available from libSQL integration.
Promise<void>Execute a transaction and automatically commit/rollback based on the task result.
The transaction may be exclusive.
As long as the transaction is converted into a write transaction,
the other async write queries will abort with database is locked error.
Note: This function is not supported on web.
Promise<void>Example
db.withExclusiveTransactionAsync(async (txn) => { await txn.execAsync('UPDATE test SET name = "aaa"'); });
Execute a transaction and automatically commit/rollback based on the task result.
Note: This transaction is not exclusive and can be interrupted by other async queries.
Promise<void>Example
db.withTransactionAsync(async () => { await db.execAsync('UPDATE test SET name = "aaa"'); // // We cannot control the order of async/await order, so order of execution is not guaranteed. // The following UPDATE query out of transaction may be executed here and break the expectation. // const result = await db.getFirstAsync<{ name: string }>('SELECT name FROM Users'); expect(result?.name).toBe('aaa'); }); db.execAsync('UPDATE test SET name = "bbb"');
If you worry about the order of execution, use withExclusiveTransactionAsync instead.
A class that represents an instance of the SQLite session extension.
See: Session Extension
SQLiteSession Methods
Apply a changeset synchronously.
Note: Running heavy tasks with this function can block the JavaScript thread and affect performance.
voidAttach a table to the session synchronously.
Note: Running heavy tasks with this function can block the JavaScript thread and affect performance.
voidClose the session synchronously.
Note: Running heavy tasks with this function can block the JavaScript thread and affect performance.
voidCreate a changeset synchronously.
Note: Running heavy tasks with this function can block the JavaScript thread and affect performance.
ChangesetCreate an inverted changeset asynchronously.
This is a shorthand for createChangesetAsync() + invertChangesetAsync().
Create an inverted changeset synchronously.
This is a shorthand for createChangesetSync() + invertChangesetSync().
Note: Running heavy tasks with this function can block the JavaScript thread and affect performance.
ChangesetEnable or disable the session synchronously.
Note: Running heavy tasks with this function can block the JavaScript thread and affect performance.
voidInvert a changeset synchronously.
Note: Running heavy tasks with this function can block the JavaScript thread and affect performance.
ChangesetA prepared statement returned by SQLiteDatabase.prepareAsync() or SQLiteDatabase.prepareSync() that can be binded with parameters and executed.
SQLiteStatement Methods
Run the prepared statement and return the SQLiteExecuteAsyncResult instance.
Promise<SQLiteExecuteAsyncResult<T>>Run the prepared statement and return the SQLiteExecuteSyncResult instance.
Note: Running heavy tasks with this function can block the JavaScript thread and affect performance.
SQLiteExecuteSyncResult<T>Finalize the prepared statement. This will call the sqlite3_finalize() C function under the hood.
Attempting to access a finalized statement will result in an error.
Note: While
expo-sqlitewill automatically finalize any orphaned prepared statements upon closing the database, it is considered best practice to manually finalize prepared statements as soon as they are no longer needed. This helps to prevent resource leaks. You can use thetry...finallystatement to ensure that prepared statements are finalized even if an error occurs.
Promise<void>Finalize the prepared statement. This will call the sqlite3_finalize() C function under the hood.
Attempting to access a finalized statement will result in an error.
Note: While
expo-sqlitewill automatically finalize any orphaned prepared statements upon closing the database, it is considered best practice to manually finalize prepared statements as soon as they are no longer needed. This helps to prevent resource leaks. You can use thetry...finallystatement to ensure that prepared statements are finalized even if an error occurs.
voidGet the column names of the prepared statement.
Promise<string[]>Key-value store backed by SQLite. This class accepts a databaseName parameter in its constructor, which is the name of the database file to use for the storage.
SQLiteStorage Methods
Alias for clearAsync() method.
Promise<void>Clears all key-value pairs from the storage asynchronously.
Promise<boolean>Clears all key-value pairs from the storage synchronously.
booleanAlias for closeAsync() method.
Promise<void>Closes the database connection asynchronously.
Promise<void>Alias for getAllKeysAsync() method.
Promise<string[]>Retrieves all keys stored in the storage asynchronously.
Promise<string[]>Retrieves all keys stored in the storage synchronously.
string[]Retrieves the value associated with the given key synchronously.
string | nullRetrieves the key at the given index synchronously.
string | nullRetrieves the number of key-value pairs stored in the storage asynchronously.
Promise<number>Retrieves the number of key-value pairs stored in the storage synchronously.
numberMerges the given value with the existing value for the given key asynchronously. If the existing value is a JSON object, performs a deep merge.
Promise<void>Merges multiple key-value pairs asynchronously. If existing values are JSON objects, performs a deep merge.
Promise<void>Removes the value associated with the given key synchronously.
booleanSets the value for the given key asynchronously. If a function is provided, it computes the new value based on the previous value.
Promise<void>Type: Class implements PromiseLike<SQLiteTaggedQueryResult<T>>
A SQL query with tagged template literals API that can be awaited directly (returns array of objects by default), or transformed using .values() or .first() methods.
This API is inspired by Bun's SQL interface:
Example
// Default: returns array of objects const users = await sql`SELECT * FROM users WHERE age > ${21}`; // Get values as arrays const values = await sql`SELECT name, age FROM users`.values(); // Returns: [["Alice", 30], ["Bob", 25]] // Get first row only const user = await sql`SELECT * FROM users WHERE id = ${1}`.first(); // With type parameter const users = await sql<User>`SELECT * FROM users`; // Mutable queries return SQLiteRunResult const result = await sql`INSERT INTO users (name) VALUES (${"Alice"})` as SQLiteRunResult; console.log(result.lastInsertRowId, result.changes); // Synchronous API const users = sql<User>`SELECT * FROM users WHERE age > ${21}`.allSync(); const user = sql<User>`SELECT * FROM users WHERE id = ${userId}`.firstSync();
SQLiteTaggedQuery Methods
Execute a query synchronously that returns rows or metadata based on query type.
Note: Running heavy tasks with this function can block the JavaScript thread and affect performance.
SQLiteTaggedQueryResult<T>Execute the query and return an async iterator over the rows.
AsyncIterableIterator<T>Example
for await (const user of sql`SELECT * FROM users`.each()) { console.log(user.name); }
Execute the query synchronously and return an iterator.
Note: Running heavy tasks with this function can block the JavaScript thread and affect performance.
IterableIterator<T>Execute the query and return the first row only. Returns null if no rows match.
Promise<T | null>Example
const user = await sql`SELECT * FROM users WHERE id = ${1}`.first();
Execute the query synchronously and return the first row.
Note: Running heavy tasks with this function can block the JavaScript thread and affect performance.
T | nullExecute the query and return rows as arrays of values (Bun-style). Each row is an array where values are in column order.
Promise<any[][]>Example
const rows = await sql`SELECT name, age FROM users`.values(); // Returns: [["Alice", 30], ["Bob", 25]]
Methods
Backup a database to another database.
Note: Running heavy tasks with this function can block the JavaScript thread and affect performance.
voidCompares two objects deeply for equality.
booleanDelete a database file.
Note: Running heavy tasks with this function can block the JavaScript thread and affect performance.
voidGiven a Uint8Array data and deserialize to memory database.
Note: Running heavy tasks with this function can block the JavaScript thread and affect performance.
SQLiteDatabaseOpen a database.
Note: Running heavy tasks with this function can block the JavaScript thread and affect performance.
SQLiteDatabaseEvent subscriptions
Add a listener for database changes.
Note: to enable this feature, you must set
enableChangeListenertotruewhen opening the database.
EventSubscriptionA Subscription object that you can call remove() on when you would like to unsubscribe the listener.
Interfaces
Extends: AsyncIterableIterator<T>
A result returned by SQLiteStatement.executeAsync().
Example
The result includes the lastInsertRowId and changes properties. You can get the information from the write operations.
const statement = await db.prepareAsync('INSERT INTO test (value) VALUES (?)'); try { const result = await statement.executeAsync(101); console.log('lastInsertRowId:', result.lastInsertRowId); console.log('changes:', result.changes); } finally { await statement.finalizeAsync(); }
Example
The result implements the AsyncIterator interface, so you can use it in for await...of loops.
const statement = await db.prepareAsync('SELECT value FROM test WHERE value > ?'); try { const result = await statement.executeAsync<{ value: number }>(100); for await (const row of result) { console.log('row value:', row.value); } } finally { await statement.finalizeAsync(); }
Example
If your write operations also return values, you can mix all of them together.
const statement = await db.prepareAsync('INSERT INTO test (name, value) VALUES (?, ?) RETURNING name'); try { const result = await statement.executeAsync<{ name: string }>('John Doe', 101); console.log('lastInsertRowId:', result.lastInsertRowId); console.log('changes:', result.changes); for await (const row of result) { console.log('name:', row.name); } } finally { await statement.finalizeAsync(); }
SQLiteExecuteAsyncResult Methods
Get all rows of the result set. This requires the SQLite cursor to be in its initial state. If you have already retrieved rows from the result set, you need to reset the cursor first by calling resetAsync(). Otherwise, an error will be thrown.
Promise<T[]>Get the first row of the result set. This requires the SQLite cursor to be in its initial state. If you have already retrieved rows from the result set, you need to reset the cursor first by calling resetAsync(). Otherwise, an error will be thrown.
Promise<T | null>Reset the prepared statement cursor. This will call the sqlite3_reset() C function under the hood.
Promise<void>Extends: IterableIterator<T>
A result returned by SQLiteStatement.executeSync().
Note: Running heavy tasks with this function can block the JavaScript thread and affect performance.
Example
The result includes the lastInsertRowId and changes properties. You can get the information from the write operations.
const statement = db.prepareSync('INSERT INTO test (value) VALUES (?)'); try { const result = statement.executeSync(101); console.log('lastInsertRowId:', result.lastInsertRowId); console.log('changes:', result.changes); } finally { statement.finalizeSync(); }
Example
The result implements the Iterator interface, so you can use it in for...of loops.
const statement = db.prepareSync('SELECT value FROM test WHERE value > ?'); try { const result = statement.executeSync<{ value: number }>(100); for (const row of result) { console.log('row value:', row.value); } } finally { statement.finalizeSync(); }
Example
If your write operations also return values, you can mix all of them together.
const statement = db.prepareSync('INSERT INTO test (name, value) VALUES (?, ?) RETURNING name'); try { const result = statement.executeSync<{ name: string }>('John Doe', 101); console.log('lastInsertRowId:', result.lastInsertRowId); console.log('changes:', result.changes); for (const row of result) { console.log('name:', row.name); } } finally { statement.finalizeSync(); }
SQLiteExecuteSyncResult Methods
Get all rows of the result set. This requires the SQLite cursor to be in its initial state. If you have already retrieved rows from the result set, you need to reset the cursor first by calling resetSync(). Otherwise, an error will be thrown.
T[]Get the first row of the result set. This requires the SQLite cursor to be in its initial state. If you have already retrieved rows from the result set, you need to reset the cursor first by calling resetSync(). Otherwise, an error will be thrown.
T | nullReset the prepared statement cursor. This will call the sqlite3_reset() C function under the hood.
voidA result returned by SQLiteDatabase.runAsync or SQLiteDatabase.runSync.
Types
The event payload for the listener of addDatabaseChangeListener
Literal type: Record
Acceptable values are: Record<string, SQLiteBindValue>
Literal type: union
Bind parameters to the prepared statement. You can either pass the parameters in the following forms:
Example
A single array for unnamed parameters.
const statement = await db.prepareAsync('SELECT * FROM test WHERE value = ? AND intValue = ?'); const result = await statement.executeAsync(['test1', 789]); const firstRow = await result.getFirstAsync();
Example
Variadic arguments for unnamed parameters.
const statement = await db.prepareAsync('SELECT * FROM test WHERE value = ? AND intValue = ?'); const result = await statement.executeAsync('test1', 789); const firstRow = await result.getFirstAsync();
Example
A single object for named parameters
We support multiple named parameter forms such as :VVV, @VVV, and $VVV. We recommend using $VVV because JavaScript allows using $ in identifiers without escaping.
const statement = await db.prepareAsync('SELECT * FROM test WHERE value = $value AND intValue = $intValue'); const result = await statement.executeAsync({ $value: 'test1', $intValue: 789 }); const firstRow = await result.getFirstAsync();
Acceptable values are: string | number | null | boolean | Uint8Array
Update function for the setItemAsync() or setItemSync() method. It computes the new value based on the previous value. The function returns the new value to set for the key.
string
Type: SQLiteBindValue[]