Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
midterm_practical/datasource.js
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
107 lines (98 sloc)
2.25 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** @format */ | |
import sqlite3 from "sqlite3"; | |
import { open } from "sqlite"; | |
// Dummy data | |
const dummyDogs = [ | |
{ | |
dogname: "Buddy", | |
breed: "Golden Retriever", | |
age: 3, | |
shots: true, | |
disposition: "Friendly", | |
monthsinshelter: 2, | |
}, | |
{ | |
dogname: "Max", | |
breed: "German Shepherd", | |
age: 5, | |
shots: true, | |
disposition: "Loyal", | |
monthsinshelter: 4, | |
}, | |
{ | |
dogname: "Bella", | |
breed: "Labrador Retriever", | |
age: 2, | |
shots: true, | |
disposition: "Playful", | |
monthsinshelter: 1, | |
}, | |
{ | |
dogname: "Lucy", | |
breed: "Bulldog", | |
age: 4, | |
shots: true, | |
disposition: "Calm", | |
monthsinshelter: 3, | |
}, | |
{ | |
dogname: "Charlie", | |
breed: "Poodle", | |
age: 6, | |
shots: true, | |
disposition: "Intelligent", | |
monthsinshelter: 5, | |
}, | |
]; | |
// Function to open the database | |
export const openDb = async () => { | |
const db = await open({ | |
filename: "./database.db", | |
driver: sqlite3.Database, | |
}); | |
// Create the dogs table if it doesn't exist | |
await db.exec(` | |
CREATE TABLE IF NOT EXISTS dogs ( | |
id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, | |
dogname TEXT, | |
breed TEXT, | |
age INTEGER, | |
shots BOOLEAN, | |
disposition TEXT, | |
monthsinshelter INTEGER | |
) | |
`); | |
return db; | |
}; | |
// Function to add a new dog to the database | |
export const addDog = async (dog) => { | |
const db = await openDb(); | |
const sql = | |
"INSERT INTO dogs (dogname, breed, age, shots, disposition, monthsinshelter) VALUES (?, ?, ?, ?, ?, ?)"; | |
const result = await db.run(sql, [ | |
dog.dogname, | |
dog.breed, | |
dog.age, | |
dog.shots, | |
dog.disposition, | |
dog.monthsinshelter, | |
]); | |
return result.lastID; | |
}; | |
// Function to add multiple dogs to the database using forEach and async/await | |
const addMultipleDogs = async (dogs) => { | |
const db = await openDb(); | |
const sql = | |
"INSERT INTO dogs (dogname, breed, age, shots, disposition, monthsinshelter) VALUES (?, ?, ?, ?, ?, ?)"; | |
dogs.forEach(async (dog) => { | |
await db.run(sql, [ | |
dog.dogname, | |
dog.breed, | |
dog.age, | |
dog.shots, | |
dog.disposition, | |
dog.monthsinshelter, | |
]); | |
}); | |
}; | |
addMultipleDogs(dummyDogs); |