Example of SQLite Database in React Native

React Native SQLite Database

Here is an example of the 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 the SQLite database, we will use the SQLite3 Native Plugin which will work in both Android and iOS. It is based on the 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 react-native-sqlite-storage?

You just have to import the library like this:

import { openDatabase } from 'react-native-sqlite-storage';

and open the database using

var db = openDatabase({ name: 'UserDatabase.db' });

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

db.transaction(function(txn) {
  txn.executeSql(
    query,                 //Query to execute as prepared statement
    argsToBePassed[],      //Argument to pass for the prepared statement
    function(tx, res) {}   //Callback function to handle the result
  );
});

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

If you want to start a new project with a specific React Native version, you can use the --version argument:

react-native init ProjectName --version X.XX.X
react-native init ProjectName --version react-native@next

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

cd ProjectName

1. Install react-native-sqlite-storage dependency to use SQLite

npm install react-native-sqlite-storage --save

2. Install following dependencies for react-navigation

npm install @react-navigation/native --save
npm install @react-navigation/stack --save
npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view --save

These commands will copy all the dependencies into your node_module directory.

CocoaPods Installation

Please use the following command to install CocoaPods

cd ios && pod install && cd ..

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.

Project Structure

We will perform complete CRUD operation in this example. Please create the following project structure and copy the code given below

Code for SQLite Database

Open the project directory and replace the following code

App.js

// Example: Example of SQLite Database in React Native
// https://aboutreact.com/example-of-sqlite-database-in-react-native
import 'react-native-gesture-handler';

import * as React from 'react';
import { Button, View, Text } from 'react-native';

import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

import HomeScreen from './pages/HomeScreen';
import RegisterUser from './pages/RegisterUser';
import UpdateUser from './pages/UpdateUser';
import ViewUser from './pages/ViewUser';
import ViewAllUser from './pages/ViewAllUser';
import DeleteUser from './pages/DeleteUser';

const Stack = createStackNavigator();

const App = () => {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="HomeScreen">
        <Stack.Screen
          name="HomeScreen"
          component={HomeScreen}
          options={{
            title: 'Home', //Set Header Title
            headerStyle: {
              backgroundColor: '#f4511e', //Set Header color
            },
            headerTintColor: '#fff', //Set Header text color
            headerTitleStyle: {
              fontWeight: 'bold', //Set Header text style
            },
          }}
        />
        <Stack.Screen
          name="View"
          component={ViewUser}
          options={{
            title: 'View User', //Set Header Title
            headerStyle: {
              backgroundColor: '#f4511e', //Set Header color
            },
            headerTintColor: '#fff', //Set Header text color
            headerTitleStyle: {
              fontWeight: 'bold', //Set Header text style
            },
          }}
        />
        <Stack.Screen
          name="ViewAll"
          component={ViewAllUser}
          options={{
            title: 'View Users', //Set Header Title
            headerStyle: {
              backgroundColor: '#f4511e', //Set Header color
            },
            headerTintColor: '#fff', //Set Header text color
            headerTitleStyle: {
              fontWeight: 'bold', //Set Header text style
            },
          }}
        />
        <Stack.Screen
          name="Update"
          component={UpdateUser}
          options={{
            title: 'Update User', //Set Header Title
            headerStyle: {
              backgroundColor: '#f4511e', //Set Header color
            },
            headerTintColor: '#fff', //Set Header text color
            headerTitleStyle: {
              fontWeight: 'bold', //Set Header text style
            },
          }}
        />
        <Stack.Screen
          name="Register"
          component={RegisterUser}
          options={{
            title: 'Register User', //Set Header Title
            headerStyle: {
              backgroundColor: '#f4511e', //Set Header color
            },
            headerTintColor: '#fff', //Set Header text color
            headerTitleStyle: {
              fontWeight: 'bold', //Set Header text style
            },
          }}
        />
        <Stack.Screen
          name="Delete"
          component={DeleteUser}
          options={{
            title: 'Delete User', //Set Header Title
            headerStyle: {
              backgroundColor: '#f4511e', //Set Header color
            },
            headerTintColor: '#fff', //Set Header text color
            headerTitleStyle: {
              fontWeight: 'bold', //Set Header text style
            },
          }}
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
};

export default App;

Mybutton.js

// Example: Example of SQLite Database in React Native
// https://aboutreact.com/example-of-sqlite-database-in-react-native
// Custom Button

import React from 'react';
import { TouchableOpacity, Text, StyleSheet } from 'react-native';

const Mybutton = (props) => {
  return (
    <TouchableOpacity style={styles.button} onPress={props.customClick}>
      <Text style={styles.text}>{props.title}</Text>
    </TouchableOpacity>
  );
};

const styles = StyleSheet.create({
  button: {
    alignItems: 'center',
    backgroundColor: '#f05555',
    color: '#ffffff',
    padding: 10,
    marginTop: 16,
    marginLeft: 35,
    marginRight: 35,
  },
  text: {
    color: '#ffffff',
  },
});

export default Mybutton;

Mytext.js

// Example: Example of SQLite Database in React Native
// https://aboutreact.com/example-of-sqlite-database-in-react-native
// Custom Text

import React from 'react';
import { TouchableHighlight, Text, StyleSheet } from 'react-native';

const Mytext = (props) => {
  return <Text style={styles.text}>{props.text}</Text>;
};

const styles = StyleSheet.create({
  text: {
    color: '#111825',
    fontSize: 18,
    marginTop: 16,
    marginLeft: 35,
    marginRight: 35,
  },
});

export default Mytext;

Mytextinput.js

// Example: Example of SQLite Database in React Native
// https://aboutreact.com/example-of-sqlite-database-in-react-native
// Custom TextInput

import React from 'react';
import { View, TextInput } from 'react-native';

const Mytextinput = (props) => {
  return (
    <View
      style={{
        marginLeft: 35,
        marginRight: 35,
        marginTop: 10,
        borderColor: '#007FFF',
        borderWidth: 1,
      }}>
      <TextInput
        underlineColorAndroid="transparent"
        placeholder={props.placeholder}
        placeholderTextColor="#007FFF"
        keyboardType={props.keyboardType}
        onChangeText={props.onChangeText}
        returnKeyType={props.returnKeyType}
        numberOfLines={props.numberOfLines}
        multiline={props.multiline}
        onSubmitEditing={props.onSubmitEditing}
        style={props.style}
        blurOnSubmit={false}
        value={props.value}
      />
    </View>
  );
};

export default Mytextinput;

HomeScreen.js

// Example: Example of SQLite Database in React Native
// https://aboutreact.com/example-of-sqlite-database-in-react-native

import React, { useEffect } from 'react';
import { View, Text, SafeAreaView } from 'react-native';
import Mybutton from './components/Mybutton';
import Mytext from './components/Mytext';
import { openDatabase } from 'react-native-sqlite-storage';

var db = openDatabase({ name: 'UserDatabase.db' });

const HomeScreen = ({ navigation }) => {
  useEffect(() => {
    db.transaction(function (txn) {
      txn.executeSql(
        "SELECT name FROM sqlite_master WHERE type='table' AND name='table_user'",
        [],
        function (tx, res) {
          console.log('item:', res.rows.length);
          if (res.rows.length == 0) {
            txn.executeSql('DROP TABLE IF EXISTS table_user', []);
            txn.executeSql(
              'CREATE TABLE IF NOT EXISTS table_user(user_id INTEGER PRIMARY KEY AUTOINCREMENT, user_name VARCHAR(20), user_contact INT(10), user_address VARCHAR(255))',
              []
            );
          }
        }
      );
    });
  }, []);

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <View style={{ flex: 1, backgroundColor: 'white' }}>
        <View style={{ flex: 1 }}>
          <Mytext text="SQLite Example" />
          <Mybutton
            title="Register"
            customClick={() => navigation.navigate('Register')}
          />
          <Mybutton
            title="Update"
            customClick={() => navigation.navigate('Update')}
          />
          <Mybutton
            title="View"
            customClick={() => navigation.navigate('View')}
          />
          <Mybutton
            title="View All"
            customClick={() => navigation.navigate('ViewAll')}
          />
          <Mybutton
            title="Delete"
            customClick={() => navigation.navigate('Delete')}
          />
        </View>
        <Text style={{ fontSize: 18, textAlign: 'center', color: 'grey' }}>
          Example of SQLite Database in React Native
        </Text>
        <Text style={{ fontSize: 16, textAlign: 'center', color: 'grey' }}>
          www.aboutreact.com
        </Text>
      </View>
    </SafeAreaView>
  );
};

export default HomeScreen;

RegisterUser.js

// Example: Example of SQLite Database in React Native
// https://aboutreact.com/example-of-sqlite-database-in-react-native
// Screen to register the user

import React, { useState } from 'react';
import {
  View,
  ScrollView,
  KeyboardAvoidingView,
  Alert,
  SafeAreaView,
  Text,
} from 'react-native';
import Mytextinput from './components/Mytextinput';
import Mybutton from './components/Mybutton';
import { openDatabase } from 'react-native-sqlite-storage';

var db = openDatabase({ name: 'UserDatabase.db' });

const RegisterUser = ({ navigation }) => {
  let [userName, setUserName] = useState('');
  let [userContact, setUserContact] = useState('');
  let [userAddress, setUserAddress] = useState('');

  let register_user = () => {
    console.log(userName, userContact, userAddress);

    if (!userName) {
      alert('Please fill name');
      return;
    }
    if (!userContact) {
      alert('Please fill Contact Number');
      return;
    }
    if (!userAddress) {
      alert('Please fill Address');
      return;
    }

    db.transaction(function (tx) {
      tx.executeSql(
        'INSERT INTO table_user (user_name, user_contact, user_address) VALUES (?,?,?)',
        [userName, userContact, userAddress],
        (tx, results) => {
          console.log('Results', results.rowsAffected);
          if (results.rowsAffected > 0) {
            Alert.alert(
              'Success',
              'You are Registered Successfully',
              [
                {
                  text: 'Ok',
                  onPress: () => navigation.navigate('HomeScreen'),
                },
              ],
              { cancelable: false }
            );
          } else alert('Registration Failed');
        }
      );
    });
  };

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <View style={{ flex: 1, backgroundColor: 'white' }}>
        <View style={{ flex: 1 }}>
          <ScrollView keyboardShouldPersistTaps="handled">
            <KeyboardAvoidingView
              behavior="padding"
              style={{ flex: 1, justifyContent: 'space-between' }}>
              <Mytextinput
                placeholder="Enter Name"
                onChangeText={(userName) => setUserName(userName)}
                style={{ padding: 10 }}
              />
              <Mytextinput
                placeholder="Enter Contact No"
                onChangeText={(userContact) => setUserContact(userContact)}
                maxLength={10}
                keyboardType="numeric"
                style={{ padding: 10 }}
              />
              <Mytextinput
                placeholder="Enter Address"
                onChangeText={(userAddress) => setUserAddress(userName)}
                maxLength={225}
                numberOfLines={5}
                multiline={true}
                style={{ textAlignVertical: 'top', padding: 10 }}
              />
              <Mybutton title="Submit" customClick={register_user} />
            </KeyboardAvoidingView>
          </ScrollView>
        </View>
        <Text style={{ fontSize: 18, textAlign: 'center', color: 'grey' }}>
          Example of SQLite Database in React Native
        </Text>
        <Text style={{ fontSize: 16, textAlign: 'center', color: 'grey' }}>
          www.aboutreact.com
        </Text>
      </View>
    </SafeAreaView>
  );
};

export default RegisterUser;

UpdateUser.js

// Example: Example of SQLite Database in React Native
// https://aboutreact.com/example-of-sqlite-database-in-react-native
// Screen to update the user

import React, { useState } from 'react';
import {
  View,
  ScrollView,
  KeyboardAvoidingView,
  Alert,
  SafeAreaView,
  Text,
} from 'react-native';
import Mytextinput from './components/Mytextinput';
import Mybutton from './components/Mybutton';
import { openDatabase } from 'react-native-sqlite-storage';

var db = openDatabase({ name: 'UserDatabase.db' });

const UpdateUser = ({ navigation }) => {
  let [inputUserId, setInputUserId] = useState('');
  let [userName, setUserName] = useState('');
  let [userContact, setUserContact] = useState('');
  let [userAddress, setUserAddress] = useState('');

  let updateAllStates = (name, contact, address) => {
    setUserName(name);
    setUserContact(contact);
    setUserAddress(address);
  };

  let searchUser = () => {
    console.log(inputUserId);
    db.transaction((tx) => {
      tx.executeSql(
        'SELECT * FROM table_user where user_id = ?',
        [inputUserId],
        (tx, results) => {
          var len = results.rows.length;
          if (len > 0) {
            let res = results.rows.item(0);
            updateAllStates(res.user_name, res.user_contact, res.user_address);
          } else {
            alert('No user found');
            updateAllStates('', '', '');
          }
        }
      );
    });
  };
  let updateUser = () => {
    console.log(inputUserId, userName, userContact, userAddress);

    if (!inputUserId) {
      alert('Please fill User id');
      return;
    }
    if (!userName) {
      alert('Please fill name');
      return;
    }
    if (!userContact) {
      alert('Please fill Contact Number');
      return;
    }
    if (!userAddress) {
      alert('Please fill Address');
      return;
    }

    db.transaction((tx) => {
      tx.executeSql(
        'UPDATE table_user set user_name=?, user_contact=? , user_address=? where user_id=?',
        [userName, userContact, userAddress, inputUserId],
        (tx, results) => {
          console.log('Results', results.rowsAffected);
          if (results.rowsAffected > 0) {
            Alert.alert(
              'Success',
              'User updated successfully',
              [
                {
                  text: 'Ok',
                  onPress: () => navigation.navigate('HomeScreen'),
                },
              ],
              { cancelable: false }
            );
          } else alert('Updation Failed');
        }
      );
    });
  };

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <View style={{ flex: 1, backgroundColor: 'white' }}>
        <View style={{ flex: 1 }}>
          <ScrollView keyboardShouldPersistTaps="handled">
            <KeyboardAvoidingView
              behavior="padding"
              style={{ flex: 1, justifyContent: 'space-between' }}>
              <Mytextinput
                placeholder="Enter User Id"
                style={{ padding: 10 }}
                onChangeText={(inputUserId) => setInputUserId(inputUserId)}
              />
              <Mybutton title="Search User" customClick={searchUser} />
              <Mytextinput
                placeholder="Enter Name"
                value={userName}
                style={{ padding: 10 }}
                onChangeText={(userName) => setUserName(userName)}
              />
              <Mytextinput
                placeholder="Enter Contact No"
                value={'' + userContact}
                onChangeText={(userContact) => setUserContact(userContact)}
                maxLength={10}
                style={{ padding: 10 }}
                keyboardType="numeric"
              />
              <Mytextinput
                value={userAddress}
                placeholder="Enter Address"
                onChangeText={(userAddress) => setUserAddress(userAddress)}
                maxLength={225}
                numberOfLines={5}
                multiline={true}
                style={{ textAlignVertical: 'top', padding: 10 }}
              />
              <Mybutton title="Update User" customClick={updateUser} />
            </KeyboardAvoidingView>
          </ScrollView>
        </View>
        <Text style={{ fontSize: 18, textAlign: 'center', color: 'grey' }}>
          Example of SQLite Database in React Native
        </Text>
        <Text style={{ fontSize: 16, textAlign: 'center', color: 'grey' }}>
          www.aboutreact.com
        </Text>
      </View>
    </SafeAreaView>
  );
};

export default UpdateUser;

ViewAllUser.js

// Example: Example of SQLite Database in React Native
// https://aboutreact.com/example-of-sqlite-database-in-react-native
// Screen to view all the user*/

import React, { useState, useEffect } from 'react';
import { FlatList, Text, View, SafeAreaView } from 'react-native';
import { openDatabase } from 'react-native-sqlite-storage';

var db = openDatabase({ name: 'UserDatabase.db' });

const ViewAllUser = () => {
  let [flatListItems, setFlatListItems] = useState([]);

  useEffect(() => {
    db.transaction((tx) => {
      tx.executeSql('SELECT * FROM table_user', [], (tx, results) => {
        var temp = [];
        for (let i = 0; i < results.rows.length; ++i)
          temp.push(results.rows.item(i));
        setFlatListItems(temp);
      });
    });
  }, []);

  let listViewItemSeparator = () => {
    return (
      <View
        style={{ height: 0.2, width: '100%', backgroundColor: '#808080' }}
      />
    );
  };

  let listItemView = (item) => {
    return (
      <View
        key={item.user_id}
        style={{ backgroundColor: 'white', padding: 20 }}>
        <Text>Id: {item.user_id}</Text>
        <Text>Name: {item.user_name}</Text>
        <Text>Contact: {item.user_contact}</Text>
        <Text>Address: {item.user_address}</Text>
      </View>
    );
  };

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <View style={{ flex: 1, backgroundColor: 'white' }}>
        <View style={{ flex: 1 }}>
          <FlatList
            data={flatListItems}
            ItemSeparatorComponent={listViewItemSeparator}
            keyExtractor={(item, index) => index.toString()}
            renderItem={({ item }) => listItemView(item)}
          />
        </View>
        <Text style={{ fontSize: 18, textAlign: 'center', color: 'grey' }}>
          Example of SQLite Database in React Native
        </Text>
        <Text style={{ fontSize: 16, textAlign: 'center', color: 'grey' }}>
          www.aboutreact.com
        </Text>
      </View>
    </SafeAreaView>
  );
};

export default ViewAllUser;

ViewUser.js

// Example: Example of SQLite Database in React Native
// https://aboutreact.com/example-of-sqlite-database-in-react-native
// Screen to view single user

import React, { useState } from 'react';
import { Text, View, Button, SafeAreaView } from 'react-native';
import Mytextinput from './components/Mytextinput';
import Mybutton from './components/Mybutton';
import { openDatabase } from 'react-native-sqlite-storage';

var db = openDatabase({ name: 'UserDatabase.db' });

const ViewUser = () => {
  let [inputUserId, setInputUserId] = useState('');
  let [userData, setUserData] = useState({});

  let searchUser = () => {
    console.log(inputUserId);
    setUserData({});
    db.transaction((tx) => {
      tx.executeSql(
        'SELECT * FROM table_user where user_id = ?',
        [inputUserId],
        (tx, results) => {
          var len = results.rows.length;
          console.log('len', len);
          if (len > 0) {
            setUserData(results.rows.item(0));
          } else {
            alert('No user found');
          }
        }
      );
    });
  };

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <View style={{ flex: 1, backgroundColor: 'white' }}>
        <View style={{ flex: 1 }}>
          <Mytextinput
            placeholder="Enter User Id"
            onChangeText={(inputUserId) => setInputUserId(inputUserId)}
            style={{ padding: 10 }}
          />
          <Mybutton title="Search User" customClick={searchUser} />
          <View style={{ marginLeft: 35, marginRight: 35, marginTop: 10 }}>
            <Text>User Id: {userData.user_id}</Text>
            <Text>User Name: {userData.user_name}</Text>
            <Text>User Contact: {userData.user_contact}</Text>
            <Text>User Address: {userData.user_address}</Text>
          </View>
        </View>
        <Text style={{ fontSize: 18, textAlign: 'center', color: 'grey' }}>
          Example of SQLite Database in React Native
        </Text>
        <Text style={{ fontSize: 16, textAlign: 'center', color: 'grey' }}>
          www.aboutreact.com
        </Text>
      </View>
    </SafeAreaView>
  );
};

export default ViewUser;

DeleteUser.js

// Example: Example of SQLite Database in React Native
// https://aboutreact.com/example-of-sqlite-database-in-react-native
// Screen to delete the user

import React, { useState } from 'react';
import { Button, Text, View, Alert, SafeAreaView } from 'react-native';
import Mytextinput from './components/Mytextinput';
import Mybutton from './components/Mybutton';
import { openDatabase } from 'react-native-sqlite-storage';

var db = openDatabase({ name: 'UserDatabase.db' });

const DeleteUser = ({ navigation }) => {
  let [inputUserId, setInputUserId] = useState('');

  let deleteUser = () => {
    db.transaction((tx) => {
      tx.executeSql(
        'DELETE FROM  table_user where user_id=?',
        [inputUserId],
        (tx, results) => {
          console.log('Results', results.rowsAffected);
          if (results.rowsAffected > 0) {
            Alert.alert(
              'Success',
              'User deleted successfully',
              [
                {
                  text: 'Ok',
                  onPress: () => navigation.navigate('HomeScreen'),
                },
              ],
              { cancelable: false }
            );
          } else {
            alert('Please insert a valid User Id');
          }
        }
      );
    });
  };

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <View style={{ flex: 1, backgroundColor: 'white' }}>
        <View style={{ flex: 1 }}>
          <Mytextinput
            placeholder="Enter User Id"
            onChangeText={(inputUserId) => setInputUserId(inputUserId)}
            style={{ padding: 10 }}
          />
          <Mybutton title="Delete User" customClick={deleteUser} />
        </View>
        <Text style={{ fontSize: 18, textAlign: 'center', color: 'grey' }}>
          Example of SQLite Database in React Native
        </Text>
        <Text style={{ fontSize: 16, textAlign: 'center', color: 'grey' }}>
          www.aboutreact.com
        </Text>
      </View>
    </SafeAreaView>
  );
};

export default DeleteUser;

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).

Output Screenshots

SQLiteExample1     SQLiteExample2     SQLiteExample3     SQLiteExample4
SQLiteExample5     SQLiteExample6     SQLiteExample7     SQLiteExample8
SQLiteExample9     SQLiteExample10     SQLiteExample11     SQLiteExample12

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

If you have any doubts 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. 🙂


Related Posts

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

  1. 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.

    Reply
    • 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.

      Reply
      • 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!!

        Reply
        • 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.

          Reply
  2. 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.

    Reply
    • 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.

      Reply
  3. 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 ?

    Reply
    • 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.

      Reply
  4. 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.

    Reply
  5. Hi Snehal Agrawal,
    It is very helpful to me. I would like to display ten items from sqlite DB by swipeing left and right in react native. can you please give an example solution..? By which I can learn more for my project.. Kindly help me out in this situation.. Thank you.

    Reply
  6. Bonjour Snehal, bon travail.
    Au fait est ce que vous pouvez créer une base de données sqlite avec 2 o 3 tables avec des clés étrangères juste comme un exemple. Je galère vraiment sur ça

    Reply
  7. hello sir
    i create a SqlLite database from react native.
    database working correctly.
    how can i found the location of database in my device and make backup?

    Reply
  8. [From Brazil]

    Olá, eu gosto muito do seu site.
    Os exemplos são sensacionais!!

    Me ajudam muito a entender e aprender React-Native.

    Parabéns e obrigado.

    Reply
  9. Hi

    Thanks for great tutorial..I just want to save array into table . So Please guide me the syntax for table creation

    Eg: [‘cat’,’dog’,’rat’] this array should save into table

    Reply
  10. I want to pass dynamic array values into where clause IN condition.
    Please suggest me a valid syntax.

    var query=`SELECT * FROM table_name nm WHERE nm.meta_data IN(?)`
    var params=[‘bird’,’elephant’] //dynamic array

    tx.executeSql(query,params,(tx, results) => {})}

    Reply
    • hey hi, I understand the situation. I have faced the same situation and found a simple way. I am not sure if it the right way or not but it worked for me. the param in your case needs a string only so you can remove the square bracket and can use it as –>
      var params = JSON.stringify(["params","array","here" ]).replace("[","").replace("]",""); it will give you array as string and you can use it.

      Reply
      • Thank you snehal. I appreciate you for responding to everyone’s doubts in this comment section.

        I followed the above suggestion. But it is asking for ‘?’ which is equal to the number of elements in an array
        For eg:
        var query=SELECT * FROM table_name nm WHERE nm.meta_data IN(?,?)// as params have two elements.It is asking two question mark
        var params=[‘bird’,’elephant’]

        I figure out another solution.
        Instead of using IN condition, I use the “OR” clause by appending it to the main query.

        var search_name=[‘bird’,’evening’] //dynamic array
        var params = [];
        var query=`SELECT DISTINCT np.pic_uri AS uri FROM new_metadata nm
        INNER JOIN new_picture np ON nm.picture_id=np.id `;
        for(let i=0;i<search_name.length;i++)
        {
        if(i == 0){
        query = query + `nm.meta_data = ? `;
        }else{
        query = query + `OR nm.meta_data = ? `;
        }
        params.push(search_name[i]);
        }
        final query= SELECT DISTINCT np.pic_uri AS uri FROM new_metadata nm INNER JOIN new_picture np ON nm.picture_id=np.id WHERE nm.meta_data = ? OR nm.meta_data = ?
        This "OR nm.meta_data = ? " is being appended to the main query based on number of elements in a dynamic array.

        Reply
  11. I don’t see where are you keeping the UserDatabase.db file? And one more thing, can you tell how can we print the path of the Database to access it later?

    Reply
  12. Hi.
    I have done all the operations you specified in order.
    But in android, the application closes as soon as it is opened and does not give any errors.
    Thanks.

    Reply
  13. Hi, Snehal!

    I’m Vitor, from Brazil. I apreciated your tutorial very much!

    Please keep working on these powerful tutorials about React Native, it helped me a lot and I’m sure it’ll help everybody interested in mobile dev.

    Thank you!

    Reply
  14. im trying insert in query. in app. it shows successfully save. but when i check my db, there is no data inside my database. i already put my database inside project folder. ./android/app/src/assests/mydb.db

    may i know where is the data is save?. i also check on my emulator device. the database showing no data inside.

    Reply
  15. Hi, Great and easy to understand write up. I have a problem, none of my register or update sql commands are working so I am not able to register a user. I’m very confused because I am not getting the “Registration failed” alert nor am I getting the success alert. Any idea of what could be wrong?

    Everything else works as should.

    Reply
  16. First of all thanks alot for this worthful and awesome tutorial

    Please correct one thing here..
    You create table in sqlite browser as “tbl_user”
    and in the code, you write queries with “table_user”

    Reply
  17. Very nice and clean. Worked on first launch (which surprised me given the age of the code). I plan to update it and post it to my public github when I get the next opportunity.

    People need more sample code that just works. Given my recent experience with time-wasting broken demos, this is a welcome change.

    Reply

Leave a Comment

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