首页指南参考教程
This is documentation for the next SDK version. For up-to-date documentation, see the latest version (SDK 51).

Expo SQLite (legacy) iconExpo SQLite (legacy)

A library that provides access to a database that can be queried through a WebSQL-like API.

Android
iOS

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

Terminal
npx expo install expo-sqlite

If you are installing this in an existing React Native app (bare workflow), start by installing expo in your project. Then, follow the additional instructions as mentioned by library's README under "Installation in bare React Native projects" section.

Usage

To-do list app

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:

Terminal
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';

Classes

Android
iOS

ExpoSQLTransactionAsync

Type: Class implements SQLTransactionAsync

Internal data structure for the async transaction API.

Android
iOS

SQLError

SQLError Properties

Android
iOS

code

Type: number

Android
iOS

message

Type: string

Android
iOS

CONSTRAINT_ERR

Type: number

Android
iOS

DATABASE_ERR

Type: number

Android
iOS

QUOTA_ERR

Type: number

Android
iOS

SYNTAX_ERR

Type: number

Android
iOS

TIMEOUT_ERR

Type: number

Android
iOS

TOO_LARGE_ERR

Type: number

Android
iOS

UNKNOWN_ERR

Type: number

Android
iOS

VERSION_ERR

Type: number

Android
iOS

SQLiteDatabase

The database returned by openDatabase()

SQLiteDatabase Properties

Deprecated Use closeAsync() instead.

Android
iOS

close

Type: () => Promise<void>

Android
iOS

version

Type: string

SQLiteDatabase Methods

Android
iOS

closeAsync()

Close the database.

Returns:

Promise<void>

Android
iOS

closeSync()

Synchronously closes the database.

Returns:

void

Android
iOS

deleteAsync()

Delete the database file.

The database has to be closed prior to deletion.

Returns:

Promise<void>

Android
iOS

exec(queries, readOnly, callback)

NameType
queriesQuery[]
readOnlyboolean
callbackSQLiteCallback

Executes the SQL statement and returns a callback resolving with the result.

Returns:

void

Android
iOS

execAsync(queries, readOnly)

NameType
queriesQuery[]
readOnlyboolean

Executes the SQL statement and returns a Promise resolving with the result.

Android
iOS

execRawQuery(queries, readOnly, callback)

NameType
queriesQuery[]
readOnlyboolean
callbackSQLiteCallback

Due to limitations on Android this function is provided to allow raw SQL queries to be executed on the database. This will be less efficient than using the exec function, please use only when necessary.

Returns:

void

Android
iOS

readTransaction(callback, errorCallback, successCallback)

NameType
callbackSQLTransactionCallback
errorCallback
(optional)
SQLTransactionErrorCallback
successCallback
(optional)
() => void

Returns:

void

Android
iOS

transaction(callback, errorCallback, successCallback)

NameTypeDescription
callbackSQLTransactionCallback

A function representing the transaction to perform. Takes a Transaction (see below) as its only parameter, on which it can add SQL statements to execute.

errorCallback
(optional)
SQLTransactionErrorCallback

Called if an error occurred processing this transaction. Takes a single parameter describing the error.

successCallback
(optional)
() => void

Called when the transaction has completed executing on the database.


Execute a database transaction.

Returns:

void

Android
iOS

transactionAsync(asyncCallback, readOnly)

NameTypeDescription
asyncCallbackSQLTransactionAsyncCallback

A SQLTransactionAsyncCallback function that can perform SQL statements in a transaction.

readOnly
(optional)
boolean

true if all the SQL statements in the callback are read only.

Default: false

Creates a new transaction with Promise support.

Returns:

Promise<void>

Methods

Android
iOS

SQLite.openDatabase(name, version, description, size, callback)

NameTypeDescription
namestring

Name of the database file to open.

version
(optional)
string-
description
(optional)
string-
size
(optional)
number-
callback
(optional)
(db: SQLiteDatabase) => void-

Open a database, creating it if it doesn't exist, and return a Database object. On disk, the database will be created under the app's documents directory, i.e. ${FileSystem.documentDirectory}/SQLite/${name}.

The version, description and size arguments are ignored, but are accepted by the function for compatibility with the WebSQL specification.

Returns:

SQLiteDatabase

Interfaces

Android
iOS

Database

Database objects are returned by calls to SQLite.openDatabase(). Such an object represents a connection to a database on your device.

Database Methods

Android
iOS

readTransaction(callback, errorCallback, successCallback)

NameType
callbackSQLTransactionCallback
errorCallback
(optional)
SQLTransactionErrorCallback
successCallback
(optional)
() => void

Returns:

void

Android
iOS

transaction(callback, errorCallback, successCallback)

NameTypeDescription
callbackSQLTransactionCallback

A function representing the transaction to perform. Takes a Transaction (see below) as its only parameter, on which it can add SQL statements to execute.

errorCallback
(optional)
SQLTransactionErrorCallback

Called if an error occurred processing this transaction. Takes a single parameter describing the error.

successCallback
(optional)
() => void

Called when the transaction has completed executing on the database.


Execute a database transaction.

Returns:

void

Database Properties

NameTypeDescription
versionstring-

Android
iOS

ResultSet

ResultSet objects are returned through second parameter of the success callback for the tx.executeSql() method on a SQLTransaction (see above).

ResultSet Properties

NameTypeDescription
insertId
(optional)
number

The row ID of the row that the SQL statement inserted into the database, if a row was inserted.

rows{ [column]: any }-
rowsAffectednumber

The number of rows that were changed by the SQL statement.


Android
iOS

ResultSetError

ResultSetError Properties

NameTypeDescription
errorError-

Android
iOS

SQLResultSetRowList

SQLResultSetRowList Methods

Android
iOS

item(index)

NameTypeDescription
indexnumber

Index of row to get.


Returns the row with the given index. If there is no such row, returns null.

Returns:

any

SQLResultSetRowList Properties

NameTypeDescription
_arrayany[]

The actual array of rows returned by the query. Can be used directly instead of getting rows through rows.item().

lengthnumber

The number of rows returned by the query.


Android
iOS

SQLTransaction

A SQLTransaction object is passed in as a parameter to the callback parameter for the db.transaction() method on a Database (see above). It allows enqueuing SQL statements to perform in a database transaction.

SQLTransaction Methods

Android
iOS

executeSql(sqlStatement, args, callback, errorCallback)

NameTypeDescription
sqlStatementstring

A string containing a database query to execute expressed as SQL. The string may contain ? placeholders, with values to be substituted listed in the arguments parameter.

args
(optional)
SQLStatementArg[]

An array of values (numbers, strings or nulls) to substitute for ? placeholders in the SQL statement.

callback
(optional)
SQLStatementCallback

Called when the query is successfully completed during the transaction. Takes two parameters: the transaction itself, and a ResultSet object (see below) with the results of the query.

errorCallback
(optional)
SQLStatementErrorCallback

Called if an error occurred executing this particular query in the transaction. Takes two parameters: the transaction itself, and the error object.


Enqueue a SQL statement to execute in the transaction. Authors are strongly recommended to make use of the ? placeholder feature of the method to avoid against SQL injection attacks, and to never construct SQL statements on the fly.

Returns:

void

Android
iOS

SQLTransactionAsync

A transaction object to perform SQL statements in async mode.

SQLTransactionAsync Methods

Android
iOS

executeSqlAsync(sqlStatement, args)

NameType
sqlStatementstring
args
(optional)
SQLStatementArg[]

Executes a SQL statement in async mode.

Deprecated Use SQLiteDatabase instead.

Android
iOS

WebSQLDatabase

Extends: Database

WebSQLDatabase Methods

Android
iOS

deleteAsync()

Delete the database file.

The database has to be closed prior to deletion.

Returns:

Promise<void>

Android
iOS

exec(queries, readOnly, callback)

NameType
queriesQuery[]
readOnlyboolean
callbackSQLiteCallback

Returns:

void

Android
iOS

Window

Window Properties

NameTypeDescription
openDatabase
(optional)
(name: string, version: string, displayName: string, estimatedSize: number, creationCallback: DatabaseCallback) => Database-

Types

Android
iOS

DatabaseCallback()

NameType
databaseDatabase
Android
iOS

Query

NameTypeDescription
argsunknown[]-
sqlstring-
Android
iOS

SQLResultSet

NameTypeDescription
insertId
(optional)
number

The row ID of the row that the SQL statement inserted into the database, if a row was inserted.

rowsSQLResultSetRowList-
rowsAffectednumber

The number of rows that were changed by the SQL statement.

Android
iOS

SQLStatementArg

Literal Type: multiple types

Acceptable values are: string | number | null

Android
iOS

SQLStatementCallback()

NameType
transactionSQLTransaction
resultSetSQLResultSet
Android
iOS

SQLStatementErrorCallback()

NameType
transactionSQLTransaction
errorSQLError
Android
iOS

SQLTransactionAsyncCallback()

A transaction callback with given SQLTransactionAsync object to perform SQL statements in async mode.

NameType
transactionSQLTransactionAsync
Android
iOS

SQLTransactionCallback()

NameType
transactionSQLTransaction
Android
iOS

SQLTransactionErrorCallback()

NameType
errorSQLError
Android
iOS

SQLiteCallback()

NameType
error
(optional)
Error | null
resultSet
(optional)
(ResultSetError | ResultSet)[]
Expo 中文网 - 粤ICP备13048890号