0

i need to known the primary key auto_increment value after an insert statement using xdevapi on mysql in nodejs.

my code is:

sqlQueries.getDBConnection(con =>
    (function inner(con) {
        var query = "INSERT INTO users (name) VALUES ('test')";
        var executeSql = con.sql(query).execute();
        con.close();
        con.done();
        return executeSql;
    }(con)).then(function (res) {
        /***********/
        doSomethingWithTheId(id);
        /***********/
        con.close();
        con.done();
    }).catch(e => {
        cl(e);
    })
);

but i don't understand how do i get the id to use it in the doSomethingWIthTheId() function.

I tried to console.log(result) but it seems like i get an array of methods but i don't know how to reach the info i need.

91DarioDev
  • 1,612
  • 1
  • 14
  • 31

2 Answers2

2

Could you give a try on this:

sqlQueries.getDBConnection(con => {
    var query = "INSERT INTO users (name) VALUES ('test')";
    var executeSql = con.sql(query).execute();
    executeSql.then(function(result) {
        let id = result.getAutoIncrementValue();
        doSomethingWithTheId(id);
    }).catch(function(err) {
        con.close();
        con.done();
    })
});

check this out for more details:

https://dev.mysql.com/doc/dev/connector-nodejs/8.0/module-Result.html https://dev.mysql.com/doc/dev/connector-nodejs/8.0/module-SqlExecute.html

Sandeep Patel
  • 4,815
  • 3
  • 21
  • 37
1

You can do something like the following:

sqlQueries.getDBConnection(con =>
    (function inner(con) {
        var query = "INSERT INTO users (name) VALUES ('test')";
        var executeSql = con.sql(query).execute();
        return executeSql;
    }(con)).then(function (res) {
        var query = "SELECT LAST_INSERT_ID();";
        var id = con.sql(query).execute();
        /***********/
        doSomethingWithTheId(id);
        /***********/
        con.close();
        con.done();
    }).catch(e => {
        cl(e);
    })
);

See this answer for more details.

Sam Chats
  • 2,271
  • 1
  • 12
  • 34