获取刚刚添加的行的最佳方式是什么,我正在使用 Heroku、Node 和 Postgres 以及 Expressjs。我希望能够做这样的事情。
app.post( '/', function( req, res ){
client.query("INSERT into ..", function( err, result ){
res.send( result.id );
});
});
理想情况下,回调将包含有关它刚刚输入的行的信息,但它的内容只是一个看起来像的对象
{ rows:[] }
有什么好的方法可以获取我刚刚添加的那一行,谢谢。
最佳答案
您可能想使用 INSERT ... RETURNING
:
The optional
RETURNING
clause causesINSERT
to compute and return value(s) based on each row actually inserted. This is primarily useful for obtaining values that were supplied by defaults, such as a serial sequence number. However, any expression using the table's columns is allowed. The syntax of theRETURNING
list is identical to that of the output list of SELECT.
所以像这样:
client.query('insert into your_table (...) values (...) returning *', function(err, result) {
// ...
});
应该让您在回调函数中获得新插入的行。
关于sql - 获取刚刚添加的行的最佳方式。 Heroku + Node + Postgres,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9026730/