Expo SQLite(旧版)提供对数据库的访问的库,可通过类似 WebSQL 的 API 进行查询。
expo-sqlite 使你的应用能够访问可通过类似 WebSQL 的 API 进行查询的数据库。数据库在应用重新启动后保留。
¥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
- npx expo install expo-sqliteIf 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
有一个示例待办事项列表应用使用此模块进行存储。
¥Importing an existing database
要使用现有的 .db 文件打开新的 SQLite 数据库,请按照以下步骤操作:
¥To open a new SQLite database using an existing .db file you already have, follow the steps below:
1
安装 expo-file-system 和 expo-asset 模块:
¥Install expo-file-system and expo-asset modules:
- npx expo install expo-file-system expo-asset2
在项目的根目录创建一个 Metro.config.js 文件,其中包含以下内容以包含 额外的资源扩展:
¥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
仅当必要时才应该使用这种执行方式。例如,当代码在事务中是无操作时。示例:
PRAGMA foreign_keys = ON;。¥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');
import * as SQLite from 'expo-sqlite/legacy';
ExpoSQLTransactionAsyncType: Class implements SQLTransactionAsync
Internal data structure for the async transaction API.
SQLErrorSQLError Properties
codeType: number
messageType: string
CONSTRAINT_ERRType: number
DATABASE_ERRType: number
QUOTA_ERRType: number
SYNTAX_ERRType: number
TIMEOUT_ERRType: number
TOO_LARGE_ERRType: number
UNKNOWN_ERRType: number
VERSION_ERRType: number
SQLiteDatabaseThe database returned by openDatabase()
SQLiteDatabase Properties
SQLiteDatabase Methods
deleteAsync()Delete the database file.
The database has to be closed prior to deletion.
Promise<void>
exec(queries, readOnly, callback)| Name | Type |
|---|---|
| queries | Query[] |
| readOnly | boolean |
| callback | SQLiteCallback |
Executes the SQL statement and returns a callback resolving with the result.
void
execAsync(queries, readOnly)| Name | Type |
|---|---|
| queries | Query[] |
| readOnly | boolean |
Executes the SQL statement and returns a Promise resolving with the result.
Promise<(ResultSetError | ResultSet)[]>
execRawQuery(queries, readOnly, callback)| Name | Type |
|---|---|
| queries | Query[] |
| readOnly | boolean |
| callback | SQLiteCallback |
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.
void
readTransaction(callback, errorCallback, successCallback)| Name | Type |
|---|---|
| callback | SQLTransactionCallback |
| errorCallback (optional) | SQLTransactionErrorCallback |
| successCallback (optional) | () => void |
void
transaction(callback, errorCallback, successCallback)| Name | Type | Description |
|---|---|---|
| callback | SQLTransactionCallback | 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.
void
transactionAsync(asyncCallback, readOnly)| Name | Type | Description |
|---|---|---|
| asyncCallback | SQLTransactionAsyncCallback | A |
| readOnly (optional) | boolean | true if all the SQL statements in the callback are read only. Default: false |
Creates a new transaction with Promise support.
Promise<void>
SQLite.openDatabase(name, version, description, size, callback)| Name | Type | Description |
|---|---|---|
| name | string | 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,descriptionandsizearguments are ignored, but are accepted by the function for compatibility with the WebSQL specification.
DatabaseDatabase objects are returned by calls to SQLite.openDatabase(). Such an object represents a
connection to a database on your device.
Database Methods
readTransaction(callback, errorCallback, successCallback)| Name | Type |
|---|---|
| callback | SQLTransactionCallback |
| errorCallback (optional) | SQLTransactionErrorCallback |
| successCallback (optional) | () => void |
void
transaction(callback, errorCallback, successCallback)| Name | Type | Description |
|---|---|---|
| callback | SQLTransactionCallback | 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.
void
Database Properties
| Name | Type | Description |
|---|---|---|
| version | string | - |
ResultSetResultSet objects are returned through second parameter of the success callback for the
tx.executeSql() method on a SQLTransaction (see above).
ResultSet Properties
| Name | Type | Description |
|---|---|---|
| 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 } | - |
| rowsAffected | number | The number of rows that were changed by the SQL statement. |
SQLResultSetRowListSQLResultSetRowList Methods
item(index)| Name | Type | Description |
|---|---|---|
| index | number | Index of row to get. |
Returns the row with the given index. If there is no such row, returns null.
any
SQLResultSetRowList Properties
| Name | Type | Description |
|---|---|---|
| _array | any[] | The actual array of rows returned by the query. Can be used directly instead of getting rows through rows.item(). |
| length | number | The number of rows returned by the query. |
SQLTransactionA 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
executeSql(sqlStatement, args, callback, errorCallback)| Name | Type | Description |
|---|---|---|
| sqlStatement | string | A string containing a database query to execute expressed as SQL. The string
may contain |
| args (optional) | SQLStatementArg[] | An array of values (numbers, strings or nulls) to substitute for |
| callback (optional) | SQLStatementCallback | Called when the query is successfully completed during the transaction. Takes
two parameters: the transaction itself, and a |
| 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.
void
SQLTransactionAsyncA transaction object to perform SQL statements in async mode.
SQLTransactionAsync Methods
executeSqlAsync(sqlStatement, args)| Name | Type |
|---|---|
| sqlStatement | string |
| args (optional) | SQLStatementArg[] |
Executes a SQL statement in async mode.
Deprecated Use
SQLiteDatabaseinstead.
WebSQLDatabaseExtends: Database
WebSQLDatabase Methods
deleteAsync()Delete the database file.
The database has to be closed prior to deletion.
Promise<void>
exec(queries, readOnly, callback)| Name | Type |
|---|---|
| queries | Query[] |
| readOnly | boolean |
| callback | SQLiteCallback |
void
WindowWindow Properties
| Name | Type | Description |
|---|---|---|
| openDatabase (optional) | (name: string, version: string, displayName: string, estimatedSize: number, creationCallback: DatabaseCallback) => Database | - |
DatabaseCallback()| Name | Type |
|---|---|
| database | Database |
Query| Name | Type | Description |
|---|---|---|
| args | unknown[] | - |
| sql | string | - |
SQLResultSet| Name | Type | Description |
|---|---|---|
| insertId (optional) | number | The row ID of the row that the SQL statement inserted into the database, if a row was inserted. |
| rows | SQLResultSetRowList | - |
| rowsAffected | number | The number of rows that were changed by the SQL statement. |
SQLStatementCallback()| Name | Type |
|---|---|
| transaction | SQLTransaction |
| resultSet | SQLResultSet |
SQLStatementErrorCallback()| Name | Type |
|---|---|
| transaction | SQLTransaction |
| error | SQLError |
SQLTransactionAsyncCallback()A transaction callback with given SQLTransactionAsync object to perform SQL statements in async mode.
| Name | Type |
|---|---|
| transaction | SQLTransactionAsync |
SQLTransactionCallback()| Name | Type |
|---|---|
| transaction | SQLTransaction |
SQLTransactionErrorCallback()| Name | Type |
|---|---|
| error | SQLError |
SQLiteCallback()| Name | Type |
|---|---|
| error (optional) | Error | null |
| resultSet (optional) | (ResultSetError | ResultSet)[] |