Building a SQLite Database with React Native: A template
import { SQLite } from 'expo-sqlite';
const db = SQLite.openDatabase('db.db');
// Creating the table
const createTable = () => {
db.transaction(tx => {
tx.executeSql(
'CREATE TABLE IF NOT EXISTS table_name (id INTEGER PRIMARY KEY NOT NULL, name TEXT NOT NULL, age INTEGER NOT NULL);'
);
});
};
// Inserting data into the table
const insertData = (id, name, age) => {
db.transaction(tx => {
tx.executeSql(
'INSERT INTO table_name (id, name, age) VALUES (?, ?, ?)',
[id, name, age]
);
});
};
// Updating data in the table
const updateData = (id, name, age) => {
db.transaction(tx => {
tx.executeSql(
'UPDATE table_name SET name = ?, age = ? WHERE id = ?',
[name, age, id]
);
});
};
// Deleting data from the table
const deleteData = id => {
db.transaction(tx => {
tx.executeSql('DELETE FROM table_name WHERE id = ?', [id]);
});
};
// Reading data from the table
const readData = () => {
return new Promise((resolve, reject) => {
db.transaction(tx => {
tx.executeSql('SELECT * FROM table_name', [], (_, { rows }) => {
resolve(rows._array);
});
});
});
};
In the above code, we are using the SQLite
module from expo-sqlite
to interact with a SQLite database in React Native. The db
constant holds the database connection created using the SQLite.openDatabase
method.
The createTable
function creates the table in the database with columns: id
, name
, and age
. The id
column is an INTEGER
data type, is the primary key and cannot be NULL
. The name
column is a TEXT
data type and cannot be NULL
. The age
column is an INTEGER
data type and cannot be NULL
.
The insertData
function takes the values of id
, name
, and age
as arguments and inserts them into the table. The updateData
function updates the values of name
and age
for a given id
. The deleteData
function deletes the row with the given id
from the table. The readData
function returns a promise that resolves with an array of objects, each representing a row in the table, containing the values of id
, name
, and age
.