【发布时间】:2021-02-10 19:35:04
【问题描述】:
我想问一下是否有办法通过 req 插入多行。身体(来自前端)。我设法创建了一种插入一行的方法,但如果可能的话,我想插入多行 task,同时只插入一次 job。
我读过一种方法是使用 json 数组并循环它,但不知道该怎么做。如果您有其他方法,那也将是一个很大的帮助!
我目前使用 node.js / express.js 作为后端,并使用 node-postgres 作为与 db 的连接。
//2. Declare an asynchronous function for the PG transaction
async function execute() {
// Promise chain for pg Pool client
const client = await pool
.connect()
.catch(err => {
console.log("\nclient.connect():", err.name);
// iterate over the error object attributes
for (item in err) {
if (err[item] = undefined) {
process.stdout.write(item + " - " + err[item] + " ");
}
}
//end the Pool instance
console.log("\n");
process.exit();
});
try {
//Initiate the Postgres transaction
await client.query("BEGIN");
try {
const sqlString = `WITH INSERTED AS (
INSERT INTO jobs (job_name) VALUES
($1) RETURNING id)
INSERT INTO tasks(
employee_id, job_id) VALUES
($2,(
SELECT id FROM inserted
))`;
const sqlValues = [job_name, employee_id
];
// Pass SQL string to the query() method
await client.query(sqlString, sqlValues, function(err, result) {
console.log("client.query() SQL result:", result);
if (err) {
console.log("\nclient.query():", err);
// Rollback before executing another transaction
client.query("ROLLBACK");
console.log("Transaction ROLLBACK called");
} else {
client.query("COMMIT");
console.log("client.query() COMMIT row count:", result.rowCount);
}
});
} catch (er) {
// Rollback before executing another transaction
client.query("ROLLBACK");
console.log("client.query():", er);
console.log("Transaction ROLLBACK called");
}
} finally {
client.release();
console.log("Client is released");
}
}
execute();
} catch (err) {
console.error(err.message);
res.status(500).send("Server Error");
}
});
谢谢!
【问题讨论】:
-
当您要插入 2 个不同的项目时,您确定要使用 $1 两次吗?
-
@FrankHeikens 哎呀,我没有注意到那个错字。谢谢!固定(第二个应该是 2 美元)
标签: node.js postgresql node-postgres