使用 Mysql 检索最后插入的 id

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31371079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 21:09:42  来源:igfitidea点击:

Retrieve last inserted id with Mysql

mysqlnode.js

提问by lopata

Good day,

再会,

I am willing to retrieve the id value of a freshly inserted row in Mysql.

我愿意在 Mysql 中检索新插入的行的 id 值。

I know there is mysqli_insert_id function, but:

我知道有 mysqli_insert_id 函数,但是:

  1. I can't specify the table
  2. Maybe there would be a risk of retrieving the wrong id, if a query is made in the meanwhile.
  3. I am using node.js MySQL
  1. 我无法指定表
  2. 如果同时进行查询,可能会有检索到错误 id 的风险。
  3. 我正在使用 node.js MySQL

I don't want to take the risk to query the highest id since there are a lot of queries, it could give me the wrong one...

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

(My id column is on auto-increment)

(我的 id 列是自动递增的)

回答by luksch

https://github.com/mysqljs/mysql#getting-the-id-of-an-inserted-rowdescribes the solution perfectly well:

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

Edit: spelling and the repo moved in github, so I changed to the current link.

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

回答by VIKAS KOHLI

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

You can also view by visiting this link https://github.com/mysqljs/mysql#getting-the-id-of-an-inserted-row

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

回答by Jaylen

I think you misunderstood the use of mysqli_insert_id()method. This method must be executed immediatelyafter the insert statement to obtain the last inserted id. if you do it my MySQL directly

我想你误解了mysqli_insert_id()方法的使用。该方法必须在插入语句后立即执行,以获取最后插入的 id。如果你直接做我的 MySQL

INSERT INTO(a,b)values(1,'test');
SELECT LAST_INSERT_ID();  -- this will display the last inserted id