w3resource

How to Use Expo SQLite in React Native?


Expo SQLite: Managing Databases in React Native Applications

Expo SQLite is a powerful library that allows developers to interact with SQLite databases in React Native projects. It is lightweight, easy to use, and ideal for managing structured data on mobile devices. This guide will provide a comprehensive overview of Expo SQLite, its syntax, usage examples, and detailed explanations.

Expo SQLite is part of the Expo ecosystem, making it easy to include database functionality in your Expo-managed or bare React Native projects.


Installing Expo SQLite

To use SQLite in an Expo app, you must install the library as follows:

# Install the Expo SQLite library
expo install expo-sqlite

Basic Syntax

Here’s the syntax for initializing and using Expo SQLite in your project:

import * as SQLite from 'expo-sqlite';

// Open or create a database
const db = SQLite.openDatabase('my_database.db');

// Execute SQL commands
db.transaction(tx => {
  tx.executeSql('SQL_QUERY_HERE', [params], successCallback, errorCallback);
});

Key Points:

  • SQLite.openDatabase(): Opens (or creates) a SQLite database.
  • transaction(): Executes a series of SQL queries in a single transaction.
  • executeSql(): Runs an SQL query with optional parameters.

Example 1: Creating and Querying a Table

Code:

import * as SQLite from 'expo-sqlite';

// Open a database or create if not existing
const db = SQLite.openDatabase('user_data.db');

// Create a table
db.transaction(tx => {
  // Create a table named 'users'
  tx.executeSql(
    'CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY NOT NULL, name TEXT, age INTEGER);',
    [], // No parameters
    () => console.log('Table created successfully'), // Success callback
    (txObj, error) => console.log('Error', error) // Error callback
  );
});

// Insert data into the table
db.transaction(tx => {
  tx.executeSql(
    'INSERT INTO users (name, age) VALUES (?, ?);',
    ['Alice', 30], // Parameters for placeholders
    () => console.log('Data inserted successfully'),
    (txObj, error) => console.log('Error', error)
  );
});

// Query data from the table
db.transaction(tx => {
  tx.executeSql(
    'SELECT * FROM users;',
    [], // No parameters
    (txObj, { rows: { _array } }) => console.log('Query results', _array), // Success callback
    (txObj, error) => console.log('Error', error) // Error callback
  );
});

Explanation:

  • Database Initialization: The SQLite.openDatabase() method creates or opens a database named user_data.db.
  • Table Creation: SQL query creates a users table if it does not already exist.
  • Data Insertion: Inserts a user record into the users table.
  • Data Query: Fetches all records from the users table and logs them to the console.

Example 2: Updating and Deleting Records

Code:

// Update a record
db.transaction(tx => {
  tx.executeSql(
    'UPDATE users SET age = ? WHERE name = ?;',
    [35, 'Alice'], // Update age to 35 where name is Alice
    () => console.log('Record updated successfully'),
    (txObj, error) => console.log('Error', error)
  );
});

// Delete a record
db.transaction(tx => {
  tx.executeSql(
    'DELETE FROM users WHERE name = ?;',
    ['Alice'], // Delete user with name Alice
    () => console.log('Record deleted successfully'),
    (txObj, error) => console.log('Error', error)
  );
});

Explanation:

  • Update Query: Updates the age of a user named Alice to 35.
  • Delete Query: Deletes the user record for Alice.

Advantages of using Expo SQLite

    1. Ease of Use: Minimal configuration with a straightforward API.

    2. Offline Capabilities: Suitable for apps that need offline functionality.

    3. Local Data Persistence: Data stored in the SQLite database remains persistent across app sessions.

    4. Integration: Works seamlessly with other Expo libraries.


Considerations when using Expo SQLite

    1. Performance: While efficient, large-scale queries might not perform as well as a server-based database.

    2. Data Syncing: Manual effort is required to sync local data with a remote server.

    3. Transactions: Ensure queries are wrapped in transactions for reliability.


Use case Scenarios

    1. To-Do List Apps: Store tasks locally for offline usage.

    2. User Profiles: Manage user data in mobile apps without requiring remote servers.

    3. Inventory Management: Keep track of items locally for small businesses.

Practical Guides to SQLite Snippets and Examples.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/sqlite/snippets/working-with-expo-sqlite.php