乐闻世界logo
搜索文章和话题

How can I access local database on react native?

1个答案

1

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:

bash
npm install react-native-sqlite-storage

Then, in your React Native project, import and use it:

javascript
import 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:

bash
npm install realm

Using Realm:

javascript
import 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.

2024年6月29日 12:07 回复

你的答案