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
testdirectory, easily integrable with the standard React NativeAwesomeProject. Simply replaceindex.ios.jsorindex.android.jswith 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)
- Create a www folder in your project's root directory.
- Place your pre-populated database file inside the www folder.
- In Xcode, add the www folder as a folder reference to your project.
- 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.