如何使用 Node.js 和 Postgresql 找到最后一个插入 ID?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37243698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I find the last insert ID with Node.js and Postgresql?
提问by Faisal
When issuing an "insert" statement to postgres, how can I get the ID of the row last inserted in the DB?
向 postgres 发出“插入”语句时,如何获取最后插入到数据库中的行的 ID?
I tried "pg", "pg-native", "pg-connection", and a bunch of other packages. For each package, I tried the sync
and async
method. I read the thing that pretends to be package documentation. I checked the source code for the packages. For the life of me I can't figure this out, and I can't believe that I'm the only person to face this issue.
我尝试了“pg”、“pg-native”、“pg-connection”和一堆其他软件包。对于每个包,我都尝试了sync
andasync
方法。我读了假装是包文档的东西。我检查了包的源代码。对于我的生活,我无法弄清楚这一点,我无法相信我是唯一面临这个问题的人。
Any insight would be greatly appreciated.
任何见解将不胜感激。
回答by grimurd
The key here is using RETURNING id
in your INSERT query.
这里的关键是RETURNING id
在您的 INSERT 查询中使用。
The pg wiki has an example that shows how this is done.
pg wiki 有一个示例说明这是如何完成的。
// Let's pretend we have a user table with the 'id' as the auto-incrementing primary key
var queryText = 'INSERT INTO users(password_hash, email) VALUES(, ) RETURNING id'
client.query(queryText, ['841l14yah', '[email protected]'], function(err, result) {
if (err) //handle error
else {
var newlyCreatedUserId = result.rows[0].id;
}
});
or with async/await
:
或与async/await
:
const result = await client.query(queryText, ['841l14yah', '[email protected]']);
const newlyCreatedUserId = result.rows[0].id;