React Native

Seamless SQLite Database Integration with React Native

Learn how to integrate SQLite with React Native for Android and iOS. Explore installation, configuration, transactions, pre-populated databases, and local offline data storage.

React NativeSQLiteMobile DevelopmentAndroidiOSOffline StorageLocal DatabaseJavaScriptCross PlatformApp Development

Seamless SQLite Database Integration with React Native

Integrating SQLite databases within your React Native applications offers a robust and efficient solution for local data management. This article provides a comprehensive guide to seamlessly integrate SQLite into your React Native projects, supporting both Android (Classic and Native) and iOS platforms. Leveraging the foundation of Chris Brody's Cordova SQLite plugin, this approach ensures consistent performance and reliability.

Key Features

  • Transactional Operations: Execute SQL transactions reliably.
  • Cross-Platform Compatibility: Supports both Android (using pure Java and Native modules) and iOS with an identical JavaScript API.
  • Pre-populated Databases: Import existing SQLite databases directly from the application bundle and sandbox.
  • Flexible JavaScript Interface: Interact with the database using plain callbacks or Promises.
  • Sample Applications: Explore practical examples in the test directory, easily integrable with the standard React Native AwesomeProject. Simply replace index.ios.js or index.android.js with the provided sample files.

This library has been rigorously tested and is compatible with React Native versions 0.40 and above, including the latest releases. It works seamlessly with XCode 7, 8, 9, and later versions, requiring no modifications or tweaks.

(Note: For XCode 7 and 8, the SQLite iOS library name suffix is tbd instead of dylib.)

iOS Integration

1. Install Dependencies

Using CocoaPods (recommended):

npm install --save react-native-sqlite-storage

Add the following to your Podfile (located in the ios subdirectory):

pod 'React', :path => '../node_modules/react-native'
pod 'react-native-sqlite-storage', :path => '../node_modules/react-native-sqlite-storage'

Alternatively, use the sample Podfile included in the package, replacing AwesomeProject with your project's name. Then, refresh the Pods installation:

pod install
# or
pod update

Without CocoaPods (Manual Linking):

npm install --save react-native-sqlite-storage
react-native link

If react-native link encounters issues, ensure rnpm and xcode are installed globally:

npm -g install rnpm xcode

For manual linking, drag the SQLite Xcode project as a dependency into your React Native Xcode project. Add libSQLite.a (from the Workspace) to the linked libraries and frameworks. Also, add sqlite3.0.tbd (for Xcode 7 and later) or libsqlite3.0.dylib (for Xcode 6 and earlier) via the "Required Libraries" view. Ensure the build paths are correctly set.

2. Require the Module

In your JavaScript file (e.g., index.ios.js), require the module:

var SQLite = require('react-native-sqlite-storage');

3. Implement Database Interactions

Use the SQLite API in your JavaScript code. The following example demonstrates basic usage. For comprehensive examples using callbacks and Promises, refer to the sample apps in the test directory (e.g., test/index.ios.callback.js and test/index.ios.promise.js).

const errorCB = (err) => {
  console.log("SQL Error: " + err);
};

const successCB = () => {
  console.log("SQL executed fine");
};

const openCB = () => {
  console.log("Database OPENED");
};

const db = SQLite.openDatabase("test.db", "1.0", "Test Database", 200000, openCB, errorCB);
db.transaction((tx) => {
  tx.executeSql('SELECT * FROM Employees a, Departments b WHERE a.department = b.department_id', [], (tx, results) => {
    console.log("Query completed");
    const len = results.rows.length;
    for (let i = 0; i < len; i++) {
      const row = results.rows.item(i);
      console.log(`Employee name: ${row.name}, Dept Name: ${row.deptName}`);
    }
  });
});

Android Integration

1. Install Dependency

npm install --save react-native-sqlite-storage

2. Update Gradle Settings

In android/settings.gradle:

include ':react-native-sqlite-storage'
project(':react-native-sqlite-storage').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-sqlite-storage/src/android')

3. Update App Module Gradle Build Script

In android/app/build.gradle:

dependencies {
  // Other dependencies
  implementation project(':react-native-sqlite-storage')
}

4. Register React Package

For newer React Native versions (0.18+):

import org.pgsqlite.SQLitePluginPackage;

public class MainApplication extends Application implements ReactApplication {
  // ...
  @Override
  protected List<ReactPackage> getPackages() {
    return Arrays.<ReactPackage>asList(
      new SQLitePluginPackage(),  // Register SQLite Plugin here
      new MainReactPackage()
    );
  }
}

5. Require and Use in JavaScript

Refer to the example provided in the iOS integration section and the sample apps in the test directory for detailed usage.

Pre-populated Database Import (iOS)

  1. Create a www folder in your project's root directory.
  2. Place your pre-populated database file inside the www folder.
  3. In Xcode, add the www folder as a folder reference to your project.
  4. Modify your openDatabase call:
SQLite.openDatabase(
  { name: "testDB", createFromLocation: 1 },
  okCallback,
  errorCallback
);

For Android, the www directory is relative to src/main/assets.

By following these steps, you can seamlessly integrate SQLite databases into your React Native applications and leverage the power of local data storage. For further support and resources, visit Defx.

Need this built?

DEFX ships react native work like this for teams worldwide.

Tell us what you're building and we'll reply within 1 business day — or grab a call slot directly.

Send a request
DEFX EditorialDEFX Team

DEFX builds AI products, ERP platforms, web and mobile apps, and Shopify, Zoho & QuickBooks integrations for teams in the US, CA, UK, UAE, AU, and IN.

Related reads

More DEFX articles on growth-focused product delivery.

Continue with the next most relevant reads on ERP delivery, AI product architecture, ecommerce systems, and mobile execution.

Explore all articles
Artificial Inteligence6 min read

Revolutionizing Knowledge Management with AI Agents: Benefits, Use Cases & Best Practices

Discover how AI agents transform knowledge management through intelligent search, automation, personalized insights, and seamless collaboration. Learn the key benefits, use cases, and best practices for modern businesses.

AI AgentsKnowledge Management
Read article
React Native3 min read

Building Cross-Platform React Native Bridges for iOS and Android

Learn how to build React Native bridges for iOS and Android to connect JavaScript with native Swift, Objective-C, and Java code. Follow this step-by-step guide to integrate platform-specific functionality into your React Native applications.

React NativeNative Bridge
Read article
Artificial Inteligence5 min read

Accelerate AI Development with DEFX's Guide to the Groq API

Learn what the Groq API is, how Groq LPUs deliver ultra-low latency AI inference, how to generate API keys through GroqCloud, integrate with Python and LangChain, and accelerate enterprise AI development with DEFX.

Groq APIGroqCloud
Read article

Contact us

Tell us what you're building.

Share your idea, timeline, and goals — we'll reply within 1 business day with the fastest path to production.

Prefer to talk it through?
  • Reply within 1 business day
  • NDA-friendly
  • US · CA · UK · UAE · AU · IN
No spam, no drip campaigns — a human reads this.