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:
1 | import { openDatabase } from 'react-native-sqlite-storage'; |
and open the database using
1 | 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.
1 2 3 4 5 6 7 | 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
This example is updated for the React Navigation 4.0+. For more about React Navigation 4 please have a look at Using React Navigation 4.0 in React Native apps.
To install the dependencies open the terminal and jump into your project
1 | cd ProjectName |
1. Install react-native-sqlite-storage
dependency to use SQLite
1 | npm install react-native-sqlite-storage --save |
2. Install react-navigation
dependency to import createAppContainer
1 | npm install react-navigation --save |
3. Install react-native-gesture-handler
dependency to support gesture navigation
1 | npm install react-native-gesture-handler --save |
4. Install react-navigation-stack
to import createStackNavigator
1 | npm install react-navigation-stack --save |
These commands will copy all the dependencies into your node_module directory.
CocoaPods Installation
After the updation of React Native 0.60, they have introduced autolinking so we do not require to link the libraries but need to install pods.
In this example we need to install the pods for react-native-gesture-handler
and react-native-sqlite-storage
.
Please use the following command to install CocoaPods
1 | cd ios && pod install && cd .. |
Database Setup
While working with React Native it provides two option:
- You can make the database in runtime.
- 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.
Example of SQLite
We will perform a complete CRUD operation in this example. Please create the following project structure and copy the code given below
Open the project directory and replace the following code
App.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | /*Example of SQLite Database in React Native*/ import React from 'react'; //For react-navigation 3.0+ //import { createAppContainer, createStackNavigator } from 'react-navigation'; //For react-navigation 4.0+ import { createAppContainer } from 'react-navigation'; 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 App = createStackNavigator({ HomeScreen: { screen: HomeScreen, navigationOptions: { title: 'HomeScreen', headerStyle: { backgroundColor: '#f05555' }, headerTintColor: '#ffffff', }, }, View: { screen: ViewUser, navigationOptions: { title: 'View User', headerStyle: { backgroundColor: '#f05555' }, headerTintColor: '#ffffff', }, }, ViewAll: { screen: ViewAllUser, navigationOptions: { title: 'View All User', headerStyle: { backgroundColor: '#f05555' }, headerTintColor: '#ffffff', }, }, Update: { screen: UpdateUser, navigationOptions: { title: 'Update User', headerStyle: { backgroundColor: '#f05555' }, headerTintColor: '#ffffff', }, }, Register: { screen: RegisterUser, navigationOptions: { title: 'Register User', headerStyle: { backgroundColor: '#f05555' }, headerTintColor: '#ffffff', }, }, Delete: { screen: DeleteUser, navigationOptions: { title: 'Delete User', headerStyle: { backgroundColor: '#f05555' }, headerTintColor: '#ffffff', }, }, }); export default createAppContainer(App); |
Mybutton.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | /*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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | /*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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | /*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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | /*Home Screen With buttons to navigate to different options*/ import React from 'react'; import { View } 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' }); export default class HomeScreen extends React.Component { constructor(props) { super(props); 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))', [] ); } } ); }); } render() { return ( <View style={{ flex: 1, backgroundColor: 'white', flexDirection: 'column', }}> <Mytext text="SQLite Example" /> <Mybutton title="Register" customClick={() => this.props.navigation.navigate('Register')} /> <Mybutton title="Update" customClick={() => this.props.navigation.navigate('Update')} /> <Mybutton title="View" customClick={() => this.props.navigation.navigate('View')} /> <Mybutton title="View All" customClick={() => this.props.navigation.navigate('ViewAll')} /> <Mybutton title="Delete" customClick={() => this.props.navigation.navigate('Delete')} /> </View> ); } } |
RegisterUser.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | /*Screen to register 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: 'UserDatabase.db' }); export default class RegisterUser extends React.Component { constructor(props) { super(props); this.state = { user_name: '', user_contact: '', user_address: '', }; } register_user = () => { var that = this; const { user_name } = this.state; const { user_contact } = this.state; const { user_address } = this.state; //alert(user_name, user_contact, user_address); if (user_name) { if (user_contact) { if (user_address) { db.transaction(function(tx) { tx.executeSql( 'INSERT INTO table_user (user_name, user_contact, user_address) VALUES (?,?,?)', [user_name, user_contact, user_address], (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('HomeScreen'), }, ], { cancelable: false } ); } else { alert('Registration Failed'); } } ); }); } else { alert('Please fill Address'); } } else { alert('Please fill Contact Number'); } } else { alert('Please fill Name'); } }; render() { return ( <View style={{ backgroundColor: 'white', flex: 1 }}> <ScrollView keyboardShouldPersistTaps="handled"> <KeyboardAvoidingView behavior="padding" style={{ flex: 1, justifyContent: 'space-between' }}> <Mytextinput placeholder="Enter Name" onChangeText={user_name => this.setState({ user_name })} style={{ padding:10 }} /> <Mytextinput placeholder="Enter Contact No" onChangeText={user_contact => this.setState({ user_contact })} maxLength={10} keyboardType="numeric" style={{ padding:10 }} /> <Mytextinput placeholder="Enter Address" onChangeText={user_address => this.setState({ user_address })} maxLength={225} numberOfLines={5} multiline={true} style={{ textAlignVertical: 'top',padding:10 }} /> <Mybutton title="Submit" customClick={this.register_user.bind(this)} /> </KeyboardAvoidingView> </ScrollView> </View> ); } } |
UpdateUser.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 | /*Screen to update the user*/ import React from 'react'; import { View, YellowBox, 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: 'UserDatabase.db' }); export default class UpdateUser extends React.Component { constructor(props) { super(props); this.state = { input_user_id: '', user_name: '', user_contact: '', user_address: '', }; } searchUser = () => { const {input_user_id} =this.state; console.log(this.state.input_user_id); db.transaction(tx => { tx.executeSql( 'SELECT * FROM table_user where user_id = ?', [input_user_id], (tx, results) => { var len = results.rows.length; console.log('len',len); if (len > 0) { console.log(results.rows.item(0).user_contact); this.setState({ user_name:results.rows.item(0).user_name, }); this.setState({ user_contact:results.rows.item(0).user_contact, }); this.setState({ user_address:results.rows.item(0).user_address, }); }else{ alert('No user found'); this.setState({ user_name:'', user_contact:'', user_address:'', }); } } ); }); }; updateUser = () => { var that=this; const { input_user_id } = this.state; const { user_name } = this.state; const { user_contact } = this.state; const { user_address } = this.state; if (user_name){ if (user_contact){ if (user_address){ db.transaction((tx)=> { tx.executeSql( 'UPDATE table_user set user_name=?, user_contact=? , user_address=? where user_id=?', [user_name, user_contact, user_address, input_user_id], (tx, results) => { console.log('Results',results.rowsAffected); if(results.rowsAffected>0){ Alert.alert( 'Success', 'User updated successfully', [ {text: 'Ok', onPress: () => that.props.navigation.navigate('HomeScreen')}, ], { cancelable: false } ); }else{ alert('Updation Failed'); } } ); }); }else{ alert('Please fill Address'); } }else{ alert('Please fill Contact Number'); } }else{ alert('Please fill Name'); } }; render() { return ( <View style={{ backgroundColor: 'white', flex: 1 }}> <ScrollView keyboardShouldPersistTaps="handled"> <KeyboardAvoidingView behavior="padding" style={{ flex: 1, justifyContent: 'space-between' }}> <Mytextinput placeholder="Enter User Id" style={{ padding:10 }} onChangeText={input_user_id => this.setState({ input_user_id })} /> <Mybutton title="Search User" customClick={this.searchUser.bind(this)} /> <Mytextinput placeholder="Enter Name" value={this.state.user_name} style={{ padding:10 }} onChangeText={user_name => this.setState({ user_name })} /> <Mytextinput placeholder="Enter Contact No" value={''+ this.state.user_contact} onChangeText={user_contact => this.setState({ user_contact })} maxLength={10} style={{ padding:10 }} keyboardType="numeric" /> <Mytextinput value={this.state.user_address} placeholder="Enter Address" onChangeText={user_address => this.setState({ user_address })} maxLength={225} numberOfLines={5} multiline={true} style={{textAlignVertical : 'top', padding:10}} /> <Mybutton title="Update User" customClick={this.updateUser.bind(this)} /> </KeyboardAvoidingView> </ScrollView> </View> ); } } |
ViewAllUser.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | /*Screen to view all the user*/ import React from 'react'; import { FlatList, Text, View } from 'react-native'; import { openDatabase } from 'react-native-sqlite-storage'; var db = openDatabase({ name: 'UserDatabase.db' }); export default class ViewAllUser extends React.Component { constructor(props) { super(props); this.state = { FlatListItems: [], }; 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)); } this.setState({ FlatListItems: temp, }); }); }); } ListViewItemSeparator = () => { return ( <View style={{ height: 0.2, width: '100%', backgroundColor: '#808080' }} /> ); }; render() { return ( <View> <FlatList data={this.state.FlatListItems} ItemSeparatorComponent={this.ListViewItemSeparator} keyExtractor={(item, index) => index.toString()} renderItem={({ item }) => ( <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> )} /> </View> ); } } |
ViewUser.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | /*Screen to view single user*/ import React from 'react'; import { Text, View, Button } 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' }); export default class ViewUser extends React.Component { constructor(props) { super(props); this.state = { input_user_id: '', userData: '', }; } searchUser = () => { const { input_user_id } = this.state; console.log(this.state.input_user_id); db.transaction(tx => { tx.executeSql( 'SELECT * FROM table_user where user_id = ?', [input_user_id], (tx, results) => { var len = results.rows.length; console.log('len', len); if (len > 0) { this.setState({ userData: results.rows.item(0), }); } else { alert('No user found'); this.setState({ userData: '', }); } } ); }); }; render() { return ( <View> <Mytextinput placeholder="Enter User Id" onChangeText={input_user_id => this.setState({ input_user_id })} style={{ padding:10 }} /> <Mybutton title="Search User" customClick={this.searchUser.bind(this)} /> <View style={{ marginLeft: 35, marginRight: 35, marginTop: 10 }}> <Text>User Id: {this.state.userData.user_id}</Text> <Text>User Name: {this.state.userData.user_name}</Text> <Text>User Contact: {this.state.userData.user_contact}</Text> <Text>User Address: {this.state.userData.user_address}</Text> </View> </View> ); } } |
DeleteUser.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | /*Screen to delete the user*/ import React from 'react'; import { Button, Text, View, 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: 'UserDatabase.db' }); export default class UpdateUser extends React.Component { constructor(props) { super(props); this.state = { input_user_id: '', }; } deleteUser = () => { var that = this; const { input_user_id } = this.state; db.transaction(tx => { tx.executeSql( 'DELETE FROM table_user where user_id=?', [input_user_id], (tx, results) => { console.log('Results', results.rowsAffected); if (results.rowsAffected > 0) { Alert.alert( 'Success', 'User deleted successfully', [ { text: 'Ok', onPress: () => that.props.navigation.navigate('HomeScreen'), }, ], { cancelable: false } ); } else { alert('Please insert a valid User Id'); } } ); }); }; render() { return ( <View style={{ backgroundColor: 'white', flex: 1 }}> <Mytextinput placeholder="Enter User Id" onChangeText={input_user_id => this.setState({ input_user_id })} style={{ padding:10 }} /> <Mybutton title="Delete User" customClick={this.deleteUser.bind(this)} /> </View> ); } } |
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 devicereact-native run-android
or on the iOS Simulator by runningreact-native run-ios
(macOS only).
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. 🙂
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
Can you please send me a test case for that. Like the sample database and the output you want. So that I can understand the query.
It can be a text table or a screenshot.
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 + ‘%’],
Very helpful post thank you great post
Welcome. 🙂
Your words will motivate me
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.
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.
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.+
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.
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.
The DB in the laptop is for the reference. It is like an APK builder picks the database from the laptop and makes the APK with that and manages the database further in the device only(Which is a copy of the database). The DB in the laptop is for the reference. Do you want to see the database of the app? in the SQLite Browser?
Here is the URL for the tutorial on How to See SQLite Database Data Saved in Device using Android Studio
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.
You can use This SQLite example to store the data and get the data anytime. Now for the left to right swipe you can use
React Native Swipeable Card View UI like Tinder example.
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
This is just simple queries like we do in our SQL. I am unable to do it this week may be in next week. Are you ok with that?
Thanks for this tutorial.
Welcome
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?
Please have a look at How to See SQLite Database Data Saved in Device using Android Studio
Is everything updated with react-native-sqlite-storage?
If you are talking about the code then yes for the library I have to see as I haven’t faced any issue with the library yet.
Hi,
Great Tutorial..
Is there a tutorial project similar to this one on how to do this with Mongo DB Atlas in React Native?
Sure I’ll do that as soon as possible.
Hi Snehal Agrawal,
Can you help in , How to sync Realm DB data to Amazon Dynamo DB, Is there any listener to do this, I am trying but unable to that thing.
Appreciating You for providing these good tutorials!!
Thank you!!
Sorry Suresh, No idea related to that 🙁
Im savind data throw my app mobile but where it save this? I look into www/Database.db but dont have data. But I select * in table have data here.
Please have a look at this example https://aboutreact.com/see-saved-data-of-the-sqlite-database-in-device/
Hi Agarawal,
Great tutorial……..
Welcome. By the way, it’s Agrawal :p
[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.
Thank you a million time Sir !!!
you just saved me from many sleepless nights sir !!!
I’m so grateful for your help sir
Glad to hear that words 🙂
what is the location of database file ? i using genymotion and i cant find it anywhere
Please have a look at https://aboutreact.com/see-saved-data-of-the-sqlite-database-in-device/
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
You have to convert it to the JSON and then have to store it as a string and at the time of fetch again convert it to the JSON.
Thanks for the response.
If you don’t mind please provide syntax for where clause
Eg:
const save_name = this.state.photos[i]
‘SELECT id FROM picture WHERE pic_name= ?;’, [save_name]
In the above “picture” is my table name, “pic_name” is column name in “picture” table.
I want to check “save_name(eg:hill.jpg)” is present in “picture table” or not.
Please help me.
Can you please try on the tool I have posted about https://aboutreact.com/sqlite-query-tester/
sir your code is awesome
1) i want to also learn REDUX that how to store TextInput value in redux store and how to show alert on button onPress
2)check stored value. If TextInput value is store or not
so i need a program on REDUX please sir help me
Sure Pankaj. I am starting the same from today itself.
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) => {})}
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.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.
Thanks for sharing. I have also sent you some other ways. Please check your mailbox too.
where .db file is stored in app?
Can you please have a look at this https://aboutreact.com/see-saved-data-of-the-sqlite-database-in-device/