Reputation: 147
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!
Upvotes: 0
Views: 78
Reputation: 1
I think it is because of the db.run in your foreach statement which is asynchronous. Try this:
const express = require("express");
const cors = require("cors");
const sqlite3 = require("sqlite3").verbose();
const app = express();
app.use(cors());
// connect to database
let db = new sqlite3.Database("./database.db", err => {
if (err) { // if fail connection don't create table
console.error(err.message);
} else {
console.log("Successful connection to the database");
// Create table first
db.run("CREATE TABLE IF NOT EXISTS Products (product TEXT, price INTEGER);", err => {
if (err) {
console.error(err.message);
} else {
console.log("Table created successfully");
// Insert data after table creation
db.run("INSERT INTO Products (product, price) VALUES ('Apple', 5.99);", err => {
if (err) {
console.error(err.message);
} else {
console.log("Data inserted successfully");
}
});
}
});
}
});
app.listen(3000, () => {
console.log("Connection: http://localhost:3000/")
});
Upvotes: 0