NitroSQLite
React Native

Your first query

Create a SQLite table, save a note, and read it in a React Native app.

First, install Nitro SQLite and build the native app. Run the following code once from app startup or an event handler. Keep database writes out of React render functions.

SQLite stores rows in tables. A primary key identifies each row. The ? placeholder binds a value separately from the SQL text.

Save and read a note

import { open } from 'react-native-nitro-sqlite'

const database = open({ name: 'notes.sqlite' })

try {
  database.execute(`
		CREATE TABLE IF NOT EXISTS notes (
			id INTEGER PRIMARY KEY,
			body TEXT NOT NULL
		)
	`)
  database.execute(
    'INSERT INTO notes (id, body) VALUES (?, ?) ON CONFLICT(id) DO UPDATE SET body = excluded.body',
    [1, 'My first note'],
  )
  const { rows } = database.execute<{ id: number; body: string }>(
    'SELECT id, body FROM notes WHERE id = ?',
    [1],
  )
  console.log(rows._array)
} finally {
  database.close()
}

The console prints:

[{ "id": 1, "body": "My first note" }]

open() creates the database file if needed. Repeating the example updates the row with ID 1. close() releases the connection and keeps the database file.

The row generic describes the TypeScript result. It does not validate values read from SQLite. Bind user supplied values as parameters, as the insert and select do here.

Keep using the same API

Use parameters and results for value conversion, database lifecycle for file locations, and sync and async for work that should not block JavaScript.

The SQLite concepts explain the database model. The API reference lists the shared connection methods and types.

On this page