我正在尝试使用
node
命令执行以下脚本来创建一个表,并在其中插入一个项目。但是,由于某种原因,我的代码在创建表之前就将项目插入表中。我尝试交换语句的索引,但它们仍然以相同的顺序执行。当我使用 sqlite3
打开数据库并手动输入命令时,一切都按预期进行。有没有办法指定我的脚本中哪个语句先执行?
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/")
})
输出:
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!
我认为这是因为 foreach 语句中的 db.run 是异步的。试试这个:
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/")
})