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.
Examples use react-native-nitro-sqlite for React Native. In NitroUI, import from nitro-sqlite with the same APIs. See supported platforms.
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 a list of parameter sets. Each set can be a positional array or a record keyed by exact placeholder names. SQLite prepares the statement once per command and clears its bindings before each run. A single array of values or a single record runs the command once.
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 or pass an empty record to run a statement once without bindings.
await db.executeBatchAsync([
{
query: 'INSERT INTO events (name, score) VALUES ($name, $score)',
params: [
{ $name: 'alpha', $score: 10 },
{ $name: 'beta', $score: 20 },
{ $name: 'gamma', $score: 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.