0
0
React-nativeHow-ToBeginner ยท 4 min read

How to Use SQLite in React Native: Simple Guide

To use SQLite in React Native, install the react-native-sqlite-storage library, link it, and then open a database connection to run SQL queries. This lets you store and retrieve data locally on the device using familiar SQL commands.
๐Ÿ“

Syntax

First, import and open a database connection. Then use transaction to run SQL commands inside a callback. Use executeSql to run queries like CREATE, INSERT, SELECT, etc.

Each executeSql takes a SQL string, optional parameters, and success/error callbacks.

javascript
import SQLite from 'react-native-sqlite-storage';

const db = SQLite.openDatabase({name: 'test.db', location: 'default'});

db.transaction(tx => {
  tx.executeSql('CREATE TABLE IF NOT EXISTS Users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT);');
  tx.executeSql('INSERT INTO Users (name) VALUES (?);', ['Alice']);
  tx.executeSql('SELECT * FROM Users;', [], (tx, results) => {
    console.log('Query completed', results.rows.raw());
  });
});
Output
Query completed [{id: 1, name: 'Alice'}]
๐Ÿ’ป

Example

This example shows how to create a table, insert a row, and read data from SQLite in a React Native app.

javascript
import React, {useEffect} from 'react';
import {View, Text} from 'react-native';
import SQLite from 'react-native-sqlite-storage';

const db = SQLite.openDatabase({name: 'test.db', location: 'default'});

export default function App() {
  const [users, setUsers] = React.useState([]);

  useEffect(() => {
    db.transaction(tx => {
      tx.executeSql('CREATE TABLE IF NOT EXISTS Users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT);');
      tx.executeSql('INSERT INTO Users (name) VALUES (?);', ['Alice']);
      tx.executeSql('SELECT * FROM Users;', [], (tx, results) => {
        const rows = results.rows.raw();
        setUsers(rows);
      });
    });
  }, []);

  return (
    <View style={{padding: 20}}>
      <Text>Users in database:</Text>
      {users.map(user => (
        <Text key={user.id}>{user.name}</Text>
      ))}
    </View>
  );
}
Output
Users in database: Alice
โš ๏ธ

Common Pitfalls

  • Not linking the native module properly after installing react-native-sqlite-storage.
  • Forgetting to wait for the database to open before running queries.
  • Not handling asynchronous callbacks correctly, causing empty or missing data.
  • Running SQL commands outside of a transaction block.
javascript
/* Wrong: Running executeSql outside transaction */
// db.executeSql('CREATE TABLE IF NOT EXISTS Users (id INTEGER PRIMARY KEY, name TEXT);');

/* Right: Always use transaction */
db.transaction(tx => {
  tx.executeSql('CREATE TABLE IF NOT EXISTS Users (id INTEGER PRIMARY KEY, name TEXT);');
});
๐Ÿ“Š

Quick Reference

Here are key commands and methods for SQLite in React Native:

CommandDescription
SQLite.openDatabase()Open or create a database connection
db.transaction(callback)Run multiple SQL commands safely
tx.executeSql(sql, params, success, error)Run a SQL query with parameters
CREATE TABLECreate a new table if it doesn't exist
INSERT INTOAdd new rows to a table
SELECTQuery data from a table
UPDATEModify existing rows
DELETERemove rows from a table
โœ…

Key Takeaways

Install and link react-native-sqlite-storage to use SQLite in React Native.
Always run SQL commands inside a transaction using executeSql.
Handle asynchronous callbacks to get query results correctly.
Use standard SQL commands to create tables and manage data locally.
Test on real devices or emulators to ensure native module works.