SQLite is a lightweight, self-contained database engine that is ideal for local storage in mobile applications. In this blog, we’ll guide you through the installation and integration process for SQLite in a React Native application, complete with code snippets.
Prerequisites:
Installation Steps:
1. Create a new React Native project:
npx react-native init SQLiteDemo
cd SQLiteDemo
2. Install the SQLite package:
npm install react-native-sqlite-storage
3. For iOS, install CocoaPods dependencies:
cd ios
pod install
cd ..
Note: In the latest React Native versions, manual linking is not required as autolinking handles this.
4. For Android, verify that the package has been autolinked. Ensure the following lines are present in your android/settings.gradle and android/app/build.gradle (usually done automatically):
android/settings.gradle
include ':react-native-sqlite-storage'
project(':react-native-sqlite-storage').projectDir = new File(rootProject.projectDir,
'../node_modules/react-native-sqlite-storage/platforms/android')
android/app/build.gradle
dependencies {
implementation project(':react-native-sqlite-storage')
}
1. Initialize SQLite
Set up a connection to the SQLite database:
import SQLite from 'react-native-sqlite-storage';
const db = SQLite.openDatabase(
{
name: 'SQLiteDemo.db',
location: 'default',
},
() => {
console.log('Database opened');
},
error => {
console.error('Error opening database:', error);
}
);
2. Create Tables
// Creating Tables
db.transaction(tx => {
tx.executeSql(
"CREATE TABLE IF NOT EXISTS Users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)",
[],
() => {
console.log('Table created successfully');
},
error => {
console.error('Error creating table:', error);
}
);
});
3. Insert Data
const insertUser = (name, age) => {
db.transaction(tx => {
tx.executeSql(
"INSERT INTO Users (name, age) VALUES (?, ?)", // Use placeholders for parameters
[name, age], // Pass parameters as an array
(result) => {
console.log('User added successfully:', result);
},
error => {
console.error('Error adding user:', error);
}
);
});
};
4. Fetch Data
const fetchUsers = () => {
db.transaction(tx => {
tx.executeSql(
"SELECT * FROM Users",
[], // Empty array for no parameters
(_, { rows: { _array } }) => { // Correctly extract rows
console.log('Fetched users:', _array);
},
error => {
console.error('Error fetching users:', error);
}
);
});
};
5. Delete Data
const deleteUser = (id) => {
db.transaction(tx => {
tx.executeSql(
"DELETE FROM Users WHERE id = ?", // Use a placeholder
[id], // Pass the id as a parameter
(result) => {
console.log("User deleted successfully:", result);
},
error => {
console.error('Error deleting user:', error);
}
);
});
};
Test the SQLite integration by calling the functions in your component:
import React, { useEffect } from 'react';
import { View, Text, Button } from 'react-native';
const App = () => {
useEffect(() => {
fetchUsers(); // Call fetchUsers on mount
}, []);
return (
<View>
<Text>SQLite Integration</Text>
<Button title="Add User" onPress={() => insertUser('John Doe', 30)} />
<Button title="Fetch Users" onPress={fetchUsers} />
</View>
);
};
export default App;
SQLite provides a robust solution for local data storage in React Native applications. With features like transactions, table creation, and CRUD operations, it is an excellent choice for offline-first apps. This guide covers the essential setup and operations needed to integrate SQLite seamlessly into your project. For more advanced features and configurations, refer to the official SQLite documentation.
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our React Native Expertise.
0