RCkumar RCkumar - 11 months ago 73
Node.js Question

how to get the last insert id from a table in DB2 using nodejs and ibm_db package

I would like to get back the primary key of the last inserted row in DB2 form node.js using ibm_db package. I tried using

select id from NEW TABLE (insert into (val1, val2, ...) values ('lorem', 'ipsum', ...))

.prepare(sql, callback)
to make DB call in node.js. The result in the callback doesn't contain any property or method to get the auto-generated key. Any help is appreciated.

Answer Source

Yes, you need to fetch the data from result after execute as below:

  conn.prepare("select * from mytab1", function (err, stmt) {
    if(err) {
      return conn.closeSync();
    stmt.execute([], function(err, result) {
      if(err) console.log(err);
      else {
        data = result.fetchAllSync();
        console.log("Fetched Data = " );
        conn.close(function () { console.log('done'); });

Check the ibm_db/test/test-basic-test.js file for details. Thanks.