I am trying to create a table with an item inserted into it upon executing the following script using the node command. However, for some reason my code is inserting the item into the table before the table is even created. I tried swapping the indexes of my statements, but they were still executed in the same order. When I open up the database with sqlite3 and manually put in the commands, everything works as expected. Is there any way to specify which statement goes first 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!
I think it is because of the db.run in your foreach statement which is asynchronous. Try this: