SQLite
Advanced
Topic 4 of 15
SQLite
SQLite is a lightweight, embedded relational database that allows React Native applications to store and query structured data locally using standard SQL syntax.
Installing SQLite
bash
npm install react-native-sqlite-storage
Opening a Database
javascript
import SQLite from 'react-native-sqlite-storage';
const db = SQLite.openDatabase(
{ name: 'app.db', location: 'default' },
() => console.log('Database opened'),
(error) => console.log(error)
);
Creating a Table
javascript
db.transaction((tx) => {
tx.executeSql(
'CREATE TABLE IF NOT EXISTS todos (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, done INTEGER)'
);
});
Inserting Data
javascript
db.transaction((tx) => {
tx.executeSql('INSERT INTO todos (title, done) VALUES (?, ?)', ['Buy groceries', 0]);
});
Querying Data
javascript
db.transaction((tx) => {
tx.executeSql('SELECT * FROM todos', [], (tx, results) => {
const rows = results.rows.raw();
setTodos(rows);
});
});
Updating and Deleting Data
javascript
tx.executeSql('UPDATE todos SET done = 1 WHERE id = ?', [todoId]);
tx.executeSql('DELETE FROM todos WHERE id = ?', [todoId]);
When to Use SQLite
SQLite is ideal for applications requiring complex queries, relationships between data, or large structured datasets, such as note-taking apps, expense trackers, or offline-first applications with relational data.
Conclusion
SQLite provides a powerful, structured way to store and query relational data locally in React Native, well suited for applications that outgrow simple key-value storage solutions like AsyncStorage.