In our previous tutorial we had learn about Creating Database and Table in SQLite, This tutorial is the second part of SQLite tutorials. Today we would learn about how we can insert data into SQLite database in react native using TextInput component on button onPress onClick event. We would use the same Database and Table we had earlier created in previous tutorial as base of current example. We would also show the entered data on Terminal window after insertion to make sure.
Contents in this project Example of Insert Data Into SQLite Database in React Native Android iOS:
1. Before getting started, you have to visit our previous tutorial about Creating Database & Table in react native. Because all the installation guide and basic database creating quires I’d explained there. Here is the link of my previous post.
2. Open your project’s main App.js file and import useState and useEffect methods. We are using functional component in our current tutorial with States. As you all know to use State in functional component we have to import the useState method useEffect. If you want to learn about functional component then here is the link.
1
|
import React, { useState, useEffect } from ‘react’;
|
3. Import SafeAreaView, Text, View, StyleSheet, Alert, TouchableOpacity and TextInput component in your project.
1
|
import { SafeAreaView, Text, View, StyleSheet, Alert, TouchableOpacity, TextInput } from ‘react-native’;
|
4. Importing openDatabase from react-native-sqlite-storage plugin. If you’re enable to know about SQLite Storage plugin then read my this tutorial.
1
|
import { openDatabase } from ‘react-native-sqlite-storage’;
|
5. Creating a global variable named as db and here we would make a new Database named as SchoolDatabase.db . This is our SQLite database in which we would perform all the data insertion.
1
|
var db = openDatabase({ name: ‘SchoolDatabase.db’ });
|
6. Creating our export default main App functional component.
1
2
3
4
5
|
export default function App() {
}
|
7. Creating 3 States named as S_Name, S_Phone and S_Address. We would use these states to store the entered data into Text input component and form there we would enter this data into SQLite table. We would also make 3 State updating method named as setName, setPhone and setAddress to update the State values.
1
2
3
|
const [S_Name, setName] = useState(”);
const [S_Phone, setPhone] = useState();
const [S_Address, setAddress] = useState(”);
|
8. Creating useEffect() method which works as Component Did Mount method we had use in class components. We would pass an empty argument in useEffect to call it once. In this method we would execute the command of creating Table in our SQLite database. Our table name is Student_Table. Our table has 4 fields student_id, student_name, student_phone and student_address.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
useEffect(() => {
db.transaction(function (txn) {
txn.executeSql(
“SELECT name FROM sqlite_master WHERE type=’table’ AND name=’Student_Table'”,
[],
function (tx, res) {
console.log(‘item:’, res.rows.length);
if (res.rows.length == 0) {
txn.executeSql(‘DROP TABLE IF EXISTS Student_Table’, []);
txn.executeSql(
‘CREATE TABLE IF NOT EXISTS Student_Table(student_id INTEGER PRIMARY KEY AUTOINCREMENT, student_name VARCHAR(30), student_phone INT(15), student_address VARCHAR(255))’,
[]
);
}
}
);
})
}, []);
|
9. Creating a function named as insertData(). In this function we would enter data into SQLite database table. The data we would use to enter is came from typed text in Text input component States.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
const insertData = () => {
db.transaction(function (tx) {
tx.executeSql(
‘INSERT INTO Student_Table (student_name, student_phone, student_address) VALUES (?,?,?)’,
[S_Name, S_Phone, S_Address],
(tx, results) => {
console.log(‘Results’, results.rowsAffected);
if (results.rowsAffected > 0) {
Alert.alert(‘Data Inserted Successfully….’);
} else Alert.alert(‘Failed….’);
}
);
});
viewStudent() ;
}
|
10. Creating a function named as viewStudent(). Inside this function we would simply print all the entered data on Terminal window. This would make sure the data is successfully entered.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
const viewStudent = () => {
db.transaction((tx) => {
tx.executeSql(
‘SELECT * FROM Student_Table’,
[],
(tx, results) => {
var temp = [];
for (let i = 0; i < results.rows.length; ++i)
temp.push(results.rows.item(i));
console.log(temp);
}
);
});
}
|
11. Creating return() block. Here we would make 1 Text component, 3 Text input components and 1 Touchable opacity component.
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
|
return (
<SafeAreaView style={{ flex: 1 }}>
<View style={styles.mainContainer}>
<Text style={{ fontSize: 24, textAlign: ‘center’, color: ‘#000’ }}>
Insert Data Into SQLite Database
</Text>
<TextInput
style={styles.textInputStyle}
onChangeText={
(text) => setName(text)
}
placeholder=“Enter Student Name”
value={S_Name} />
<TextInput
style={styles.textInputStyle}
onChangeText={
(text) => setPhone(text)
}
placeholder=“Enter Student Phone Number”
keyboardType={‘numeric’}
value={S_Phone} />
<TextInput
style={[styles.textInputStyle, { marginBottom: 20 }]}
onChangeText={
(text) => setAddress(text)
}
placeholder=“Enter Student Address”
value={S_Address} />
<TouchableOpacity
style={styles.touchableOpacity}
onPress={insertData}>
<Text style={styles.touchableOpacityText}> Click Here To Insert Data Into SQLite Database </Text>
</TouchableOpacity>
</View>
</SafeAreaView>
);
|
12. Creating Style.
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
|
const styles = StyleSheet.create({
mainContainer: {
flex: 1,
alignItems: ‘center’,
padding: 10,
},
touchableOpacity: {
backgroundColor: ‘#0091EA’,
alignItems: ‘center’,
borderRadius: 8,
justifyContent: ‘center’,
alignItems: ‘center’,
width: ‘100%’
},
touchableOpacityText: {
color: ‘#FFFFFF’,
fontSize: 23,
textAlign: ‘center’,
padding: 8
},
textInputStyle: {
height: 45,
width: ‘90%’,
textAlign: ‘center’,
borderWidth: 1,
borderColor: ‘#00B8D4’,
borderRadius: 7,
marginTop: 15,
},
});
|
13. Complete Source Code for App.js file:
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
140
141
142
143
144
145
146
147
148
149
150
|
import React, { useState, useEffect } from ‘react’;
import { SafeAreaView, Text, View, StyleSheet, Alert, TouchableOpacity, TextInput } from ‘react-native’;
import { openDatabase } from ‘react-native-sqlite-storage’;
var db = openDatabase({ name: ‘SchoolDatabase.db’ });
export default function App() {
const [S_Name, setName] = useState(”);
const [S_Phone, setPhone] = useState();
const [S_Address, setAddress] = useState(”);
useEffect(() => {
db.transaction(function (txn) {
txn.executeSql(
“SELECT name FROM sqlite_master WHERE type=’table’ AND name=’Student_Table'”,
[],
function (tx, res) {
console.log(‘item:’, res.rows.length);
if (res.rows.length == 0) {
txn.executeSql(‘DROP TABLE IF EXISTS Student_Table’, []);
txn.executeSql(
‘CREATE TABLE IF NOT EXISTS Student_Table(student_id INTEGER PRIMARY KEY AUTOINCREMENT, student_name VARCHAR(30), student_phone INT(15), student_address VARCHAR(255))’,
[]
);
}
}
);
})
}, []);
const insertData = () => {
db.transaction(function (tx) {
tx.executeSql(
‘INSERT INTO Student_Table (student_name, student_phone, student_address) VALUES (?,?,?)’,
[S_Name, S_Phone, S_Address],
(tx, results) => {
console.log(‘Results’, results.rowsAffected);
if (results.rowsAffected > 0) {
Alert.alert(‘Data Inserted Successfully….’);
} else Alert.alert(‘Failed….’);
}
);
});
viewStudent() ;
}
const viewStudent = () => {
db.transaction((tx) => {
tx.executeSql(
‘SELECT * FROM Student_Table’,
[],
(tx, results) => {
var temp = [];
for (let i = 0; i < results.rows.length; ++i)
temp.push(results.rows.item(i));
console.log(temp);
}
);
});
}
return (
<SafeAreaView style={{ flex: 1 }}>
<View style={styles.mainContainer}>
<Text style={{ fontSize: 24, textAlign: ‘center’, color: ‘#000’ }}>
Insert Data Into SQLite Database
</Text>
<TextInput
style={styles.textInputStyle}
onChangeText={
(text) => setName(text)
}
placeholder=“Enter Student Name”
value={S_Name} />
<TextInput
style={styles.textInputStyle}
onChangeText={
(text) => setPhone(text)
}
placeholder=“Enter Student Phone Number”
keyboardType={‘numeric’}
value={S_Phone} />
<TextInput
style={[styles.textInputStyle, { marginBottom: 20 }]}
onChangeText={
(text) => setAddress(text)
}
placeholder=“Enter Student Address”
value={S_Address} />
<TouchableOpacity
style={styles.touchableOpacity}
onPress={insertData}>
<Text style={styles.touchableOpacityText}> Click Here To Insert Data Into SQLite Database </Text>
</TouchableOpacity>
</View>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
mainContainer: {
flex: 1,
alignItems: ‘center’,
padding: 10,
},
touchableOpacity: {
backgroundColor: ‘#0091EA’,
alignItems: ‘center’,
borderRadius: 8,
justifyContent: ‘center’,
alignItems: ‘center’,
width: ‘100%’
},
touchableOpacityText: {
color: ‘#FFFFFF’,
fontSize: 23,
textAlign: ‘center’,
padding: 8
},
textInputStyle: {
height: 45,
width: ‘90%’,
textAlign: ‘center’,
borderWidth: 1,
borderColor: ‘#00B8D4’,
borderRadius: 7,
marginTop: 15,
},
});
|
Screenshots: