I am having an issue creating a table and inserting an item into it using the node
command. Despite my efforts to reorganize my script, the item is being inserted before the table is created. Interestingly, manually inputting the commands in sqlite3
works as expected. Is there a way to control the order of execution in my script?
index.js
const express = require("express");
const cors = require("cors");
const sqlite3 = require("sqlite3").verbose();
const app = express();
app.use(cors());
let db = new sqlite3.Database("./database.db", err => {
try {
console.log("Successful connection to the database");
} catch {
console.error(err.message);
}
});
statements = ["CREATE TABLE IF NOT EXISTS Products (product TEXT, price INTEGER);", "INSERT INTO Products (product, price) VALUES ('Apple', 5.99);"]
statements.forEach(statement => db.run(statement, err => {
try {
console.log(statement + ": successful!");
} catch {
console.error(err.message);
}
}));
app.listen(3000, () => {
console.log("Connection: http://localhost:3000/")
})
Output:
Connection: http://localhost:3000/
Successful connection to the database
INSERT INTO Products (product, price) VALUES ('Apple', 5.99);: successful!
CREATE TABLE IF NOT EXISTS Products (product TEXT, price INTEGER);: successful!