Skip to content

Instantly share code, notes, and snippets.

@exlnt
Last active February 5, 2022 15:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save exlnt/f9d59b60406d80b71565e9e90a52ce67 to your computer and use it in GitHub Desktop.
Save exlnt/f9d59b60406d80b71565e9e90a52ce67 to your computer and use it in GitHub Desktop.
SQL Lite DB helper class used in React-Native EXPO app.
import * as Constants from "../constants/constants";
import * as SQLite from "expo-sqlite";
const db = SQLite.openDatabase(Constants.SQLLITE_Database_Name);
export default class BudgetCategoryDB {
// Init DB and create table
initDB() {
return new Promise((resolve) => {
db.transaction((tx) => {
tx.executeSql(
"CREATE TABLE IF NOT EXISTS BudgetCategory(CategoryId INTEGER PRIMARY KEY AUTOINCREMENT, CategoryName VARCHAR(20), CategoryType varchar(10), CategoryColor VARCHAR(10))",
[],
() => resolve(db),
() => console.log("Init DB failed!")
);
});
});
}
// Get all budget categories
listBudgetCategories() {
return new Promise((resolve) => {
this.initDB().then((db) => {
db.transaction((tx) => {
tx.executeSql(
"select * from BudgetCategory Order By CategoryType, CategoryName",
[],
(tx, { rows }) => {
resolve(rows._array);
},
() => console.log("listBudgetCategories failed!")
);
});
});
});
}
createBudgetCategory(newCategory) {
let sqlOK = false;
return new Promise((resolve) => {
this.initDB().then((db) => {
db.transaction((tx) => {
tx.executeSql(
"INSERT INTO BudgetCategory (CategoryName, CategoryType, CategoryColor) VALUES (?,?,?)",
[newCategory.categoryName, newCategory.type, newCategory.color],
(trans, results) => {
if (results.rowsAffected > 0) {
sqlOK = true;
}
},
() => resolve(false)
);
tx.executeSql(
"select * from BudgetCategory Where CategoryName=?",
[newCategory.categoryName],
(trans, results) => {
if (!sqlOK && results.rows.length == 0) {
resolve(false);
} else {
resolve(true);
}
}
);
});
});
});
}
changeBudgetCategory(Category) {
let sqlOK = false;
return new Promise((resolve) => {
this.initDB().then((db) => {
db.transaction((tx) => {
tx.executeSql(
"Update BudgetCategory Set CategoryName=?, CategoryType=?, CategoryColor=? Where CategoryId=?",
[
Category.categoryName,
Category.type,
Category.color,
Category.categoryId,
],
(trans, results) => {
if (results.rowsAffected == 0) {
resolve(false);
} else {
resolve(true);
}
},
() => resolve(false)
);
});
});
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment