Sqlite is the sql database engine for the mobile devices. It provides the relational database features as in the SQL only the difference is the basic syntax format. Expo has recently added the support for the SQLite for RN (React Native). In this post I will simply share a insert operation only.
First import the SQLite from the Expo and initialize a database
1 2 |
import {SQLite} from "expo"; const db = SQLite.openDatabase('test.db'); |
Next we have to write a code to define our schema
1 2 3 4 5 |
db.transaction(tx => { tx.executeSql("PRAGMA foreign_keys=on"); tx.executeSql("CREATE TABLE IF NOT EXISTS [Class]([ClassId] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, [ClassName] NVARCHAR(50) NULL)"); tx.executeSql("CREATE TABLE IF NOT EXISTS [Students] ([StudentId] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,[StudentName] NVARCHAR(50) NULL,[isPresent] NVARCHAR(50) DEFAULT false NOT NULL,[ClassId] INTEGER NOT NULL,FOREIGN KEY(ClassId) REFERENCES Class(ClassId))"); }); |
The “PRAGMA foreign_keys=on” is required while maintaining the relationship of one entity with the other one. In the above schema a ‘Class’ and ‘Student’ has one-to-many relationship.
For the basic example , let’s start with the basic insert command .
1 2 3 4 5 6 7 8 9 10 11 12 |
export const insert = (classname) => new Promise((resolve,reject) => { db.transaction(tx=> { tx.executeSql("insert into [Class](ClassName) values (?)",[classname]); tx.executeSql("select * from [Class]",[], (_, { rows : {_array} }) => { if(_array){ resolve(_array); } else { reject("Error in insert method."); } }) }); }); |
You can save all these code inside a Schema.js file and call the insert function passing any string. In the next part, we will get started with the CRUD operation and showing the data in the FlatList.