Building apps with Expo? Need to store data on the device? That’s where SQLite comes in! It’s like having a small, fast, and reliable database inside your app. In this guide, I’ll explain step-by-step how to use SQLite in the easiest way possible. I’ll include examples you can copy and real-world scenarios where you’ll actually use this.
Let’s get started! 🚀
What’s SQLite, and Why Should You Use It?
SQLite is a super lightweight and fast database that works without a server. This means:
- You don’t need an internet connection to store or retrieve data.
- It’s great for small apps or features like saving user info, settings, or local lists.
- It’s easy to set up and use in your Expo projects.
Setting Up SQLite in Expo
Here’s how to add SQLite to your app in just a few steps:
1. Install SQLite in Your Expo Project
Open your terminal and run this command:
expo install expo-sqlite
This adds the SQLite library to your project.
2. Create or Open a Database
You can open an existing database or create a new one. Here’s how:
import * as SQLite from 'expo-sqlite';
// Open or create a database
const db = SQLite.openDatabase('myApp.db');
That’s it! You’ve set up your database and are ready to store some data. 🎉
How to Use SQLite:
Let’s look at some common tasks like creating tables, adding data, and retrieving it. I’ll keep it simple with easy examples.
1. Creating a Table
A table is like a spreadsheet where you store your data. Let’s create a table to save user information.
db.transaction(tx => {
tx.executeSql(
`CREATE TABLE IF NOT EXISTS Users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
email TEXT,
age INTEGER
);`,
[],
() => console.log('Table created!'),
(_, error) => console.error('Error creating table:', error)
);
});
What’s happening here?
CREATE TABLE IF NOT EXISTS
ensures the table is only created if it doesn’t already exist.- Each column (like
name
,email
, andage
) is where specific data will go. id
is unique for every user, and it increases automatically.
When would you use this?
When your app needs to save user details like name, email, and age.
2. Adding Data
Let’s add a new user to our Users
table.
db.transaction(tx => {
tx.executeSql(
`INSERT INTO Users (name, email, age) VALUES (?, ?, ?);`,
['Jane Doe', 'Zee.Shan@example.com', 25],
(_, result) => console.log('User added!', result),
(_, error) => console.error('Error adding user:', error)
);
});
What’s happening here?
- The
?
placeholders are filled with the values:Jane Doe
, her email, and age. - This method is secure and prevents hacking attempts (like SQL injection).
When would you use this?
When a new user signs up or provides their information.
3. Retrieving Data
Want to see the users you’ve saved? Here’s how to fetch all the data from the Users
table.
db.transaction(tx => {
tx.executeSql(
`SELECT * FROM Users;`,
[],
(_, { rows: { _array } }) => console.log('Users:', _array),
(_, error) => console.error('Error fetching users:', error)
);
});
What’s happening here?
SELECT *
means “get everything” from theUsers
table.- The result is an array of rows (users) that you can display in your app.
When would you use this?
When you want to show a list of users, like on a profile or dashboard page.
4. Updating Data
Let’s say you want to update a user’s email. Here’s how:
db.transaction(tx => {
tx.executeSql(
`UPDATE Users SET email = ? WHERE id = ?;`,
['new.email@example.com', 1],
() => console.log('User updated!'),
(_, error) => console.error('Error updating user:', error)
);
});
What’s happening here?
- The
SET
clause changes the email tonew.email@example.com
. - The
WHERE
clause ensures only the user withid = 1
is updated.
When would you use this?
When a user edits their profile or updates their contact info.
5. Deleting Data
Want to remove a user? Let’s delete the user with id = 1
.
db.transaction(tx => {
tx.executeSql(
`DELETE FROM Users WHERE id = ?;`,
[1],
() => console.log('User deleted!'),
(_, error) => console.error('Error deleting user:', error)
);
});
What’s happening here?
DELETE FROM Users
removes data from the table.WHERE id = 1
ensures only the user with that ID is deleted.
When would you use this?
When a user account is removed or data needs to be cleaned up.
Real-World Use Cases
Here’s where you can use SQLite in your app:
- User Profiles: Save names, emails, and other details for offline access.
- To-Do Lists: Store tasks or notes locally on the device.
- Settings: Save app settings like themes, preferences, or language options.
- Offline Data: Cache data when the user is offline and sync it later.
Wrapping Up
SQLite is a fantastic tool to manage data locally in your Expo apps. By learning these simple queries, you can:
- Create tables for organizing data.
- Add, retrieve, update, and delete data effortlessly.
It’s perfect for offline-friendly apps or features like saving user profiles, tasks, or settings.
Ready to try it? Start small—set up SQLite in your app and see how easy it is! If you need help, I’ve got you. Reach out anytime at codewithzeeeshan.me. Let’s build awesome databases together! 😊
Happy coding! 🎉