Batch operations
Execute a fixed list of statements in one native transaction.
Use db.executeBatch() or db.executeBatchAsync() to run a fixed list of statements together. A transaction commits the whole list or rolls it back if a command fails. A batch also avoids a separate JavaScript call for each write.
Run a batch
Pass a nonempty list of commands. Each batch uses an exclusive transaction. A failure throws or rejects, and the result of a successful batch contains the sum of rowsAffected; it does not include SELECT rows.
import type { BatchQueryCommand } from 'react-native-nitro-sqlite'
const commands: BatchQueryCommand[] = [
{
query: 'INSERT INTO events (name, score) VALUES (?, ?)',
params: ['start', 1],
},
{
query: 'INSERT INTO events (name, score) VALUES (?, ?)',
params: ['finish', 2],
},
]
const { rowsAffected } = await db.executeBatchAsync(commands)Repeat a statement with different values
When the same SQL runs with different values, give one command an array of parameter arrays. The native batch code expands it into separate executions before starting the transaction.
An empty params array skips that command. If every command has an empty array, the batch throws or rejects because it has nothing to execute. Omit params for a statement that should run once without bindings, such as CREATE TABLE.
await db.executeBatchAsync([
{
query: 'INSERT INTO events (name, score) VALUES (?, ?)',
params: [
['alpha', 10],
['beta', 20],
['gamma', 30],
],
},
])Choose the async form for a large batch so database work runs off the JavaScript thread. The synchronous form blocks until the batch finishes. Both participate in the open() connection's operation ordering. An empty batch is an error. Do not call a batch method from inside a transaction callback on the same connection; use the callback's tx methods instead. For exact types, see BatchQueryCommand and BatchQueryResult.