2016-05-15 8 views
2

postgresに "insert"文を発行すると、最後にDBに挿入された行のIDを取得するにはどうすればよいですか?Node.jsとPostgresqlで最後の挿入IDを見つけるにはどうしたらいいですか?

"pg"、 "pg-native"、 "pg-connection"などのパッケージを試しました。各パッケージについて、私はsyncasyncメソッドを試しました。パッケージ化されたドキュメントのようなものを読んだ。パッケージのソースコードを確認しました。私の人生のために、これを理解することはできません。私はこの問題に直面する唯一の人だとは信じられません。

洞察力があれば幸いです。

答えて

6

私はこれをテストしていないことを認め、私は以前はpgを使ったことがないと認めて始めます。

私がドキュメントから収集したことは、クエリオブジェクトが結果オブジェクトを持つイベント 'row'と 'end'を放出することです。私はこの結果オブジェクトにあなたのIDが含まれていると信じています。

var client = new Client('postgres://brian:[email protected]:5432/dev'); 

var query = client.query('INSERT INTO sometable VALUES ('foo', 'bar')'); 
query.on('row', function(row, result) { 
    // As I understand it, this will append all the affected rows to the  
    // result object so that they can be accessed in the 'end' event. 
    result.addRow(row); 
}); 
query.on('end', function(result) { 
    // result.rows should contain the data you inserted along with the 
    // id that was generated. 
    console.log(result.rows.length + ' rows were received'); 
}); 

これは何らかの形で役立ちます。しかし、私はこのモジュールを使用する上での専門家であるとふりを言いません:) pg wikiはan example that shows how this is doneです。

//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($1, $2) RETURNING id' 
client.query(queryText, ['841l14yah', '[email protected]'], function(err, result) { 
    if(err) //handle error 
    else { 
    var newlyCreatedUserId = result.rows[0].id; 
    } 
}); 
+0

最初の調査では最初の手法を試しましたが、うまくいかなかった。しかし、 "復帰id"の部分は決して私には起こりませんでした。多くのありがとう:) – Faisal

+0

編集された答えはとてもシンプルです –

関連する問題