Example of SQLite Database in React Native

Example of SQLite Database in React Native

Here is an Example of SQLite Database in React Native. We are hoping you have read our previous post on Local Database in React Native App. SQLite database is one of the databases that we have discussed in our previous post. To define the SQLite we can say it is an open source SQL database that stores data to a text file on a device. We can perform all the CRUD SQL transactions in this database and it is the most common database that we have heard of for mobile development. Let’s get started.

For SQLite database, we will use the SQLite3 Native Plugin which will work in both Android and iOS. It is based on Cordova SQLite plugin.

In this Example, we will make a HomeScreen with the option to go to other screens like

  • RegisterUser: To Register the User. (Create/Insert)
  • ViewAllUser: To View All Users. (Read)
  • ViewUser: To View Singel Users By Id. (Read)
  • UpdateUser: To Update the User.(Update)
  • DeleteUser: To Delete the User.

We will be having some custom components like Mybutton, Mytext, Mytextinput which will be used in place of react-native Button, Text, and TextInput.

How to Use

You just have to import the library like this:

and open the database using

Now, whenever you need to make some database call you can use db variable to execute the database query.

Please note down we are using callback function not real-time feedback because while running a query it does not provide the response instantly. Execution of query takes some time and give the response in the callback function.

To Make a React Native App

Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react-native init to make our React Native App. Assuming that you have node installed, you can use npm to install the react-native-cli command line utility. Open the terminal and go to the workspace and run
npm install -g react-native-cli
Run the following commands to create a new React Native project
react-native init ProjectName
This will make a project structure with an index file named App.js in your project directory.

Installation of Dependencies

To install the dependencies open the terminal and jump into your project

1. To use openDatabase we need to install react-native-sqlite-storage dependency.
Run the following command.

2. In this Example, we are going to use createStackNavigator component to navigate so you need to install react-navigation and react-native-gesture-handler dependencies. If you are new to React Navigation then visit Switch from One Screen to another using React Navigation 3.+ (Router) this will help you.
Run the following commands

This command will copy all the dependencies into your node_module directory. –save is optional, it is just to update dependencies in your package.json file.

Linking of Dependencies

After installing the dependencies you need to link it with your project using

After linking the dependency if you face  Could not Compile Settings File project/android/settings.gradle error while building and installing the project then you can find the solution here.

This Linking will link react-native-gesture-handler and react-native-sqlite-storage but in some cases, Linker does not link the Android (IOS linking is fine, the problem is with Android only) project properly so please link the Android project manually. To link Android project please follow the below steps (If your Android project is properly linked then you can check and skip the step)

Go to the SqliteExample> android > app > build.gradle.
Scroll down and add the following dependency.

Open SqliteExample> android > settings.gradle and add the following lines.

Open SqliteExample> android > app > src > main > java > com > sqliteexample> MainApplication.java  and add the following lines in imports.

Scroll down and add the following line in getPackages after new MainReactPackage(). Please add a comma(,) and then add

 

Here we have done with our installation of the library. If you are still facing the trouble please comment below so that we can help you out from the problem.

Database Setup

While working with React Native it provides two option:

  1. You can make the database in runtime.
  2. You can use the pre-populated database so that you can start working directly.

In this example, we will make the database on runtime and for the pre-populated database, You can visit Example of Pre Populated SQLite Database in React Native.

Just to confirm the dependencies here is the screenshot of the dependencies that we are using :

If you are on the same boat then let’s go further or please update your package.json and run npm install to install new dependencies.

For this Example, we are using the following structure. You have to make page directory in SqliteExample and components directory under that. Make the marked js files too.

You can download the code from Github and can run directly

OR

Open the project directory and replace the following code

App.js

Mybutton.js

Mytext.js

Mytextinput.js

HomeScreen.js

RegisterUser.js

UpdateUser.js

ViewAllUser.js

ViewUser.js

DeleteUser.js

To Run the React Native App

Open the terminal again and jump into your project using.
cd ProjectName
To run the project on an Android Virtual Device or on real debugging device
react-native run-android
or on the iOS Simulator by running
react-native run-ios (macOS only).

If you are facing null is not an object (Evaluating ‘NativeModules[“SQLite”][method]’) like the screenshot below.

Then open SQLiteProject/node_modules/react-native-sqlite-storage/src/android/build.gradle
and replace

with

As I was using the react-native:0.58.4 and the defined version was react-native:0.14.+, so just removed the version and added plus(+) for the latest version available and it worked for me. I have also updated compile with implementation because of Gradle 3.+ that Google announced at IO17. If you have no idea about the compile to implementation update then you can visit here, You will find the detailed answer to your question.

Here are the screenshots of the final outcome.

               
               
               

This is how you can use SQLite Database in React Native Application. If you want to see how to use pre-populated SQLite database then please visit Example of Pre Populated SQLite Database in React Native.

If you have any doubt or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!

Hope you liked it. 🙂

How useful was this post?

Click on a star to rate us!

Average rating / 5. Vote count:

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

48 thoughts on “Example of SQLite Database in React Native”

  1. I am doing POC on Sqlite with React Native. when i try execute below line getting complie time error. import org.pgsqlite.SQLitePluginPackage, it is expecting from value

    • Can you please check the SQLite version you are using?
      We have used the following version for the example. If you are using any other version then please let me know so that we can run the trial with that or share the screenshot of the log to help you out.
      “react-native-sqlite-storage”: “^3.3.6”,

    • Hello Naresh,
      Finally, I faced the same problem now and find a solution. Please open the following file

      SqliteProject/node_modules/react-native-sqlite-storage/src/android/build.gradle

      and replace
      compile ‘com.facebook.react:react-native:0.14.+’ (Or other version)
      with
      compile ‘com.facebook.react:react-native:+’

      This will solve your problem.

  2. Hello,
    why using setstate in constructor in VIEWAllUSERS.js ?
    because in react lifecycle we should not use setstate in constructor

    • Setting up state in constructor means you are assigning some default value to the state variable. If you do not want to setState in constructor you can skip it but if you try to get the value without setting the value then it will give you a state undefined error so you have to remember that first set the state and then get the value from state.

  3. I am using SQLite version 3.3.9. I am trying to run on the ios, i get the following error on the screen –

    null is not an object (evaluating ‘NativeModules[“SQLite”][method]’)

    exec
    sqlite.core.js:88:26
    open
    sqlite.core.js:279:16
    SQLitePlugin
    sqlite.core.js:110:12

    sqlite.core.js:778:26

    sqlite.core.js:77:22

    HomeScreen.js:30:11
    loadModuleImplementation
    require.js:321:6

    App.js:13
    loadModuleImplementation
    require.js:321:6

    index.js:7
    loadModuleImplementation
    require.js:321:6
    guardedLoadModule
    require.js:199:45
    global code
    :0

    • Are you talking about React?
      Web platform does not support SQL database. You can use the browser database to store the data in your browser. Can you please confirm which web technology you want to use?

  4. Hello my name is jose carlos, this is a great example to be able to integrate sqlite to react native I only have a question that I will appreciate the quick answer.

    How can I check where this database is physically stored in order to open it with a manager and check its data?

  5. I wanted to know one more thing about the sql
    query I see that in the example do a SELECT of a field but as it would be
    if I want to look for part of the id, the name of the user in the same query,
    I would appreciate your help. Thanks in advance

      • already great look this is my table and I did a like to search by name but in addition to search by name I want to search by its id
        tx.executeSql(
        “SELECT * FROM tabla1 where name like ?”,
        [‘%’ + input_user + ‘%’],

        • Try this:

          The concept is you can add as many as “?” you want in place of dynamic values and after that, you have to pass the array of values you want to pass but please be aware to manage the sequence of the values.

          tx.executeSql(
          “SELECT * FROM tabla1 where id = ? AND name like ?”,
          [id_value_here, ‘%’ + input_user + ‘%’],

  6. i have run on android device getting error please help

    Information:java: Errors occurred while compiling module ‘app’
    Information:javac 1.8.0_152-release was used to compile java sources
    /Users/developers/Desktop/Pratibha/SqliteExample-React-Native-master/android/app/src/main/java/com/sqliteexample/MainActivity.java
    Error:(3, 26) java: cannot find symbol
    symbol: class ReactActivity
    location: package com.facebook.react
    Error:(5, 35) java: cannot find symbol
    symbol: class ReactActivity
    Error:(11, 5) java: method does not override or implement a method from a supertype
    /Users/developers/Desktop/Pratibha/SqliteExample-React-Native-master/android/app/src/main/java/com/sqliteexample/MainApplication.java
    Error:(5, 26) java: cannot find symbol
    symbol: class ReactApplication
    location: package com.facebook.react
    Error:(8, 26) java: cannot find symbol
    symbol: class ReactNativeHost
    location: package com.facebook.react
    Error:(16, 61) java: cannot find symbol
    symbol: class ReactApplication
    Error:(18, 17) java: cannot find symbol
    symbol: class ReactNativeHost
    location: class com.sqliteexample.MainApplication
    Error:(40, 10) java: cannot find symbol
    symbol: class ReactNativeHost
    location: class com.sqliteexample.MainApplication
    Error:(18, 56) java: cannot find symbol
    symbol: class ReactNativeHost
    location: class com.sqliteexample.MainApplication
    Error:(39, 3) java: method does not override or implement a method from a supertype

  7. Hi, Where and How to handle onUpgrade() version increase of DB. Thanks for good article. It really helped alot to learn React Native with SQLITE.

    • Hello Nikhil,
      I think you are from the Android Development Background. Let me tell you in case of React Native you don’t have the way like android to upgrade the database, if you want to upgrade the database then you need to drop the table by the query. For this, you can manage the database version on your own.
      If you need some suggestion then you can use the following example
      Example: If you are releasing your application put the application version somewhere on the server and check the version from the application. if the application version and the server application version is same then go ahead else drop the old database and make a new one.

      • Hi, in that case it is fine. But my question was, I have released the app with some Database version and if in next release I need to alter the table without deleting existing data, As in android and in iOS we do have version management, onUpgrade function will call, How to manage such scenario as its very important in offline apps. Thanks!!

        • Hello Nikhil,

          In that case, you have to manage it using the database version. For example, I have a customer table in an offline database with [id, name, address] now you need to add pin code in the table. So in the next release create a global variable with name DB_VERSION =1.1 and make sync varriableDB_VERSION.
          Now on the starting of the app check whether async DB_VERSION is equal to DB_VERSION in the global variable. If they are equal just move else
          1. Copy the data from the old customer table into an array.
          2. Drop the old table.
          3. Create a new one.
          4. Insert the copied array from array to new table.
          5. insert the DB_VESRION of the global variable into Async Storage.

          Thus you can alter the table in the live application. I have done it one of my application. Can you please see and suggest if any problem in this concept? as it is working fine in my case.

  8. I have a question I created a base like in the point: You can make the database in runtime. How can I view the base physically in SQLite? e.g. View records in the database.

    • 1. For Android connect the device which has the application now open the project in Android Studio and You can see the option called “Device File Explore” in the rightmost upper/bottom corner.

      2. Now click the option and data > data and your application package name which can be found in the AndroidManifest.xml file (It is something link xyz.abd.kjh).

      3. you can right-click to save the database and it can be opened via SQLite Browser.

      Can you please check your inbox for further information.

  9. app.js
    import React from ‘react’;
    //For React Navigation Version 2+
    //import {createStackNavigator} from ‘react-navigation’;
    //For React Navigation Version 3+
    import {createStackNavigator,createAppContainer} from ‘react-navigation’;
    import LoginUser from ‘./pages/LoginUser.js’;
    import SignUp from ‘./pages/SignUp.js’;

    const App = createStackNavigator({
    login: {
    screen: LoginUser,
    navigationOptions: {
    title: ‘Login’,
    headerStyle: { backgroundColor: ‘#f05555’ },
    headerTintColor: ‘#ffffff’,
    },
    },
    signUp: {
    screen: SignUp,
    navigationOptions: {
    title: ‘SignUp’,
    headerStyle: { backgroundColor: ‘#f05555’ },
    headerTintColor: ‘#ffffff’,
    },
    },
    });
    export default createAppContainer(App);
    ——————————-loginUser.js
    import React from ‘react’;
    //For React Navigation Version 2+
    //import {createStackNavigator} from ‘react-navigation’;
    //For React Navigation Version 3+
    import {createStackNavigator,createAppContainer} from ‘react-navigation’;
    import LoginUser from ‘./pages/LoginUser.js’;
    import SignUp from ‘./pages/SignUp.js’;

    const App = createStackNavigator({
    login: {
    screen: LoginUser,
    navigationOptions: {
    title: ‘Login’,
    headerStyle: { backgroundColor: ‘#f05555’ },
    headerTintColor: ‘#ffffff’,
    },
    },
    signUp: {
    screen: SignUp,
    navigationOptions: {
    title: ‘SignUp’,
    headerStyle: { backgroundColor: ‘#f05555’ },
    headerTintColor: ‘#ffffff’,
    },
    },
    });
    export default createAppContainer(App);

    —————————-signup.js
    /*Screen to signup the user*/
    import React from ‘react’;
    import { View, ScrollView, KeyboardAvoidingView, Alert } from ‘react-native’;
    import Mytextinput from ‘./components/Mytextinput’;
    import Mybutton from ‘./components/Mybutton’;
    import { openDatabase } from ‘react-native-sqlite-storage’;
    var db = openDatabase({ name: ‘FirstAppDB.db’ });

    export default class SignUp extends React.Component {
    constructor(props) {
    super(props);
    this.state = {
    email: ”,
    password: ”,
    cpassword: ”,
    };
    }
    signup_user = () => {
    var that = this;
    const { email } = this.state;
    const { password } = this.state;
    const { cpassword } = this.state;
    //alert(user_name, user_contact, user_address);
    if (email) {
    if (password) {
    if (cpassword) {
    db.transaction(function(tx) {
    alert(“email”);
    tx.executeSql(
    ‘INSERT INTO signup (email, password, cpassword) VALUES (?,?,?)’,
    [email, password, cpassword],
    (tx, results) => {
    console.log(‘Results’, results.rowsAffected);
    if (results.rowsAffected > 0) {

    Alert.alert(
    ‘Success’,
    ‘You are Registered Successfully’,
    [
    {
    text: ‘Ok’,
    onPress: () =>
    that.props.navigation.navigate(‘login’),
    },
    ],
    { cancelable: false }
    );
    } else {
    alert(‘Registration Failed’);
    }
    }
    );
    });
    } else {
    alert(‘Please fill confirm password’);
    }
    } else {
    alert(‘Please fill password’);
    }
    } else {
    alert(‘Please fill email’);
    }
    };

    render() {
    return (

    this.setState({ email })}
    style={{ padding:10 }}
    />
    this.setState({ password })}
    maxLength={10}
    style={{ padding:10 }}
    />
    this.setState({ cpassword })}
    maxLength={10}
    style={{padding:10 }}
    />

    );
    }
    }

    MyButton.js,MyTextInput.js,MyText.js is same as yours
    Here alert is not work in tx.executeSql
    so whta is the problem

    the button is not working of signup and login

  10. Hello sir ! thanks for the tutorial I tried but can’t build my project BUILD FAILED *What went wrong: java.io.IOException unable to delete directory D:\test\node_modules\react-native-sqlite-storage\src\android\build\generated\source\buildConfig\debug.
    how can i solve this…?

    • Hello Gulshan,
      Just delete D:\testpro\node_modules\react-native-sqlite-storage\src\android\build\generated\ directory and run again. This is a usual problem after Android Studio 3.+

  11. I am facing following error on ios.
    Module AppRegistry is not a registered callable module (calling runApplication)

    __callFunction
    MessageQueue.js:355:6

    MessageQueue.js:106:26
    __guard
    MessageQueue.js:314:10
    callFunctionReturnFlushedQueue
    MessageQueue.js:105:17
    callFunctionReturnFlushedQueue
    [native code]:0

  12. Hello,
    I read your post on local storage in React Native and It was very helpful compared to other post I have been reading.
    Thank You, for that first.

    Now my question is,

    I need offline storage,
    And when I mean that, I need the database to be persisted even after the app is un installed.
    How to go about that ?

    • Hello Madara,
      Thank you for your words. 🙂
      If we talk about your query then it is not possible. Device OS removes the database and everything related to the application when we uninstall the app. The only thing that remains is the external files like images and videos.
      If you want you can export the database and can take the backup of it and when user installed the app you can import that again but the files are visible to the user so he/she can remove it also.

  13. Hi,

    i am new to react-native. for this tutorial i have all the steps you have mentioned but, while build had failed with below exception. Can you please suggest how to resolve it?
    Error:
    info Starting JS server…
    info Building and installing the app on the device (cd android && gradlew.bat app:installDebug)…
    C:\Users\Rajesh\.gradle\caches\modules-2\files-2.1\com.squareup.okhttp3\okhttp\3.12.1\dc6d02e4e68514eff5631963e28ca7742ac69efe\okhttp-3.12.1.jar: D8: Type org.conscrypt.Conscrypt was not found, it is required for default or static interface methods desugaring of java.security.Provider okhttp3.internal.platform.ConscryptPlatform.getProvider()
    > Task :react-native-sqlite-storage:mergeDebugJniLibFolders FAILED

    FAILURE: Build failed with an exception.

    * What went wrong:
    Execution failed for task ‘:react-native-sqlite-storage:mergeDebugJniLibFolders’.
    > Failed to create directory ‘C:\Users\Rajesh\Documents\Studies\Practice\SqlExample\node_modules\react-native-sqlite-storage\src\android\build\intermediates\incremental\mergeDebugJniLibFolders’

    * Try:
    Run with –stacktrace option to get the stack trace. Run with –info or –debug option to get more log output. Run with –scan to get full insights.

    * Get more help at https://help.gradle.org

    Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
    Use ‘–warning-mode all’ to show the individual deprecation warnings.
    See https://docs.gradle.org/5.4.1/userguide/command_line_interface.html#sec:command_line_warnings

    BUILD FAILED in 51s

  14. Hello Snehal,

    I am able to see data over android mobile. But while opening the database locally on laptop which is connected to mobile , it is showing empty db in sqlite browser. I followed the steps that you mentioned while replying to @ola’s question.
    How to proceed further?
    One more doubt, are we able to have .db copy in phone memory also? If yes, what is the location.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

About React will use the information you provide on this form to be in touch with you and to provide updates and marketing.