【问题标题】:mysql xdevapi nodejs: returning the inserted row auto_increment idmysql xdevapi nodejs:返回插入的行auto_increment id
【发布时间】:2019-12-29 00:47:07
【问题描述】:

我需要知道在 nodejs 中在 mysql 上使用 xdevapi 插入语句后的主键 auto_increment 值。

我的代码是:

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);
    })
);

但我不明白如何获取 id 以在 doSomethingWIthTheId() 函数中使用它。

我尝试 console.log(result) 但似乎我得到了一系列方法,但我不知道如何获得我需要的信息。

【问题讨论】:

    标签: mysql sql node.js


    【解决方案1】:

    您可以执行以下操作:

    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);
        })
    );
    

    查看answer了解更多详情。

    【讨论】:

      【解决方案2】:

      你可以试试这个吗:

      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();
          })
      });
      

      查看更多详情:

      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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-15
        • 1970-01-01
        • 2011-11-06
        • 2014-09-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多