使用Mysql检索最后插入的id

lop*_*ata 51 mysql node.js

美好的一天,

我愿意在Mysql中检索刚插入的行的id值.

我知道有mysqli_insert_id函数,但是:

  1. 我无法指定表格
  2. 如果同时进行查询,则可能存在检索错误ID的风险.
  3. 我正在使用node.js MySQL

我不想冒险查询最高的ID,因为有很多查询,它可能会给我错误的...

(我的id列是自动增量)

luk*_*sch 106

https://github.com/mysqljs/mysql#getting-the-id-of-an-inserted-row 非常好地描述了解决方案:

connection.query('INSERT INTO posts SET ?', {title: 'test'}, function(err, result) {
  if (err) throw err;

  console.log(result.insertId);
});
Run Code Online (Sandbox Code Playgroud)

编辑:拼写和在github中移动的repo,所以我改为当前链接.

  • 嗨Raghav,如果你的密钥不是自动递增而不是数据库创建,你不应该像这样检索它.毕竟,您应该已经将密钥放在编程逻辑中的某个位置.如果你挣扎,我建议你在SO上创建一个关于这个问题的独立问题. (3认同)
  • @luksch uuid()是mysql的一个函数,在数据库上创建,他不知道uuid是什么,直到调用insert into语句. (3认同)
  • 如果有[多个“insert”语句](//stackoverflow.com/q/39270007/4928642)怎么办? (2认同)
  • 主键是非自增类型怎么办?我使用 uuid 作为主键的 BINARY(16) 。 (2认同)

VIK*_*HLI 5

var table_data =  {title: 'test'};

connection_db.query('INSERT INTO tablename SET ?', table_data , function(err, result, fields) {
  if (err) {
      // handle error
    }else{
       // Your row is inserted you can view  
      console.log(result.insertId);
    }
});
Run Code Online (Sandbox Code Playgroud)

您也可以通过访问以下链接进行查看:https://github.com/mysqljs/mysql#getting-the-id-of-an-inserted-row