Getting Started With SQLite In React Native

Introduction

React Native is a popular framework for creating cross-platform mobile apps with JavaScript and React. It has numerous UI components, API calls, and other capabilities that make it simple to create complex mobile applications. However, storing and managing data in a mobile app might be difficult. This is where SQLite comes in. SQLite is a lightweight and embedded database that can store data in a mobile app. In this article, we'll look at how to use SQLite with React Native to store and manage data. So, without further ado, let us begin.

Get a complete understanding of React Native with our detailed article- Introduction To React Native.

STEP 1. Install SQLite react native package

The first step is to install the react-native-SQLite-storage package. You can install the package using the below command,

npm i react-native-sqlite-storage

STEP 2. Create a database

Create and establish a database connection after installing the react-native-SQLite-storage package.

//database connection
const db = SQLite.openDatabase({
        name: 'mydb',
        location: 'default'
    },
    () => {
        console.log("Database connected!")
    }, //on success
    error => console.log("Database error", error) //on error
)

STEP 3. Create a Table

Ohe executeSql method of the database object allows you to execute SQL statements. Once you have a database connection, you can create a table. n the below code, I am creating a user table to store the user details, like id, email, and name.

useEffect(() => {
    createUserTable(); //call create table function here
})
//create table function
const createUserTable = () => {
    db.executeSql("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, email VARCHAR, name VARCHAR)", [], (result) => {
        console.log("Table created successfully");
    }, (error) => {
        console.log("Create table error", error)
    })
}

STEP 4. Add a record

IToinsert data into the table, you will need to use the executeSql method again with the INSERT INTO statement. In the below code, we are creating a user.

//insert a new user record
const createUser = () => {
    let sql = "INSERT INTO users (email, name) VALUES (?, ?)";
    let params = ["[email protected]", "MD Sarfaraj"]; //storing user data in an array
    db.executeSql(sql, params, (result) => {
        Alert.alert("Success", "User created successfully.");
    }, (error) => {
        console.log("Create user error", error);
    });
}

STEP 5. Fetch records

The executeSql method can be used with a SELECT statement to retrieve data from the table. We are retrieving the list of users from the user's table, as shown below.

//list all the users
const listUsers = async () => {
    let sql = "SELECT * FROM users";
    db.transaction((tx) => {
        tx.executeSql(sql, [], (tx, resultSet) => {
            var length = resultSet.rows.length;
            for (var i = 0; i < length; i++) {
                console.log(resultSet.rows.item(i));
            }
        }, (error) => {
            console.log("List user error", error);
        })
    })
}

STEP 5. Update a record

We will use the same executeSql method with a SQL update statement to update the table data. In the below code, we are updating a user email and name.

//update user record
const updateUser = () => {
    let sql = 'UPDATE users SET email = ?, name = ? WHERE id = ?';
    let params = ['[email protected]', "Mohammad Sarfaraj", 1];
    db.executeSql(sql, params, (resultSet) => {
        Alert.alert("Success", "Record updated successfully");
    }, (error) => {
        console.log(error);
    });
}

STEP 6. Delete a record

To delete the data from the table, we will use the same executeSql method with the DELETE statement; in the below code, we delete a user using their id.

//delete user record
const deleteUser = () => {
    let sql = "DELETE FROM users WHERE id = ?";
    let params = [1];
    db.executeSql(sql, params, (resultSet) => {
        Alert.alert("Success", "User deleted successfully");
    }, (error) => {
        console.log("Delete user error", error);
    })
}

Conclusion

In conclusion, using SQLite with React Native is a great way to store and manage data in your mobile app. With the react-native-SQLite-storage package, you can easily open a database connection, create tables, insert data, and query data using standard SQL statements. This provides a reliable and efficient way to store and retrieve data in a mobile app.

SQLite is a lightweight and fast database that is well-suited for mobile apps. It provides a simple and easy-to-use API for working with data, and it's a great choice for small to medium-sized databases. If you're building a mobile app with React Native and need to store data, SQLite is definitely worth considering.

Reference 

Please see the GitHub repository linked below for a better understanding, 


Similar Articles