In React Native, accessing local databases typically involves using popular libraries for data storage and retrieval. The most commonly used libraries are SQLite and Realm. Below, I will detail how to use these two approaches to access local databases.
Using SQLite
SQLite is a lightweight database, ideal for mobile devices. The React Native community provides several wrapper libraries for SQLite, such as react-native-sqlite-storage.
Installation and Setup:
First, install this library:
bashnpm install react-native-sqlite-storage
Then, in your React Native project, import and use it:
javascriptimport SQLite from 'react-native-sqlite-storage'; // Open or create the database const db = SQLite.openDatabase({name: 'my.db', location: 'default'}, () => { console.log('Database successfully opened or created'); }, err => { console.error('Error opening database: ', err); }); // Using the database db.transaction(tx => { // Create table tx.executeSql('CREATE TABLE IF NOT EXISTS Users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)', []); // Insert data tx.executeSql('INSERT INTO Users (name, age) VALUES (?, ?)', ['John', 30]); // Query data tx.executeSql('SELECT * FROM Users', [], (tx, results) => { var len = results.rows.length; for (let i = 0; i < len; i++) { let row = results.rows.item(i); console.log(`User ID: ${row.id}, Name: ${row.name}, Age: ${row.age}`); } }); });
Using Realm
Realm is another popular cross-platform lightweight database solution suitable for React Native. It offers richer data models and query capabilities.
Installation and Configuration:
First, install Realm:
bashnpm install realm
Using Realm:
javascriptimport Realm from 'realm'; // Define the model and schema class User extends Realm.Object {} User.schema = { name: 'User', primaryKey: 'id', properties: { id: 'int', name: 'string', age: 'int', }, }; // Open the database let realm = new Realm({schema: [User]}); // Write data realm.write(() => { realm.create('User', { id: 1, name: 'John', age: 30, }); }); // Read data let users = realm.objects('User'); console.log('Number of users:', users.length); users.forEach(user => { console.log(`User ID: ${user.id}, Name: ${user.name}, Age: ${user.age}`); });
In both approaches, you can choose the appropriate database solution based on your project's requirements and complexity. SQLite is suitable for more traditional SQL operations, while Realm provides a more modern data management approach.