【问题标题】:Retrieve last inserted id with Mysql使用 Mysql 检索最后插入的 id
【发布时间】:2015-09-30 23:48:31
【问题描述】:

早安,

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

我知道有mysqli_insert_id函数,但是:

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

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

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

【问题讨论】:

  • 是什么让您认为必须指定插入的表才能获取 ID?到目前为止,您尝试了哪些方法来使其发挥作用?

标签: mysql node.js


【解决方案1】:

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

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

  console.log(result.insertId);
});

【讨论】:

  • 如果有multiple insert statements怎么办?
  • 我的主键是非递增类型怎么办?我使用 uuid 作为主键的 BINARY(16)。
  • 您好 Raghav,如果您的密钥不是自动递增的且未创建数据库,则您不需要像这样检索它。毕竟,您应该在编程逻辑的某个地方已经有了密钥。如果您遇到困难,我建议您在 SO 上创建一个关于此的独立问题。
  • @luksch uuid()是mysql的一个函数,创建在数据库上,直到调用insert into语句他才知道uuid是什么。
  • 当我使用 console.log(result.insertId) 时。它工作得很好。但是当发送 response.send(result.insertId) 它会抛出错误。为什么会这样?
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:
    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);
        }
    });
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-29
      • 2012-12-23
      • 2019-05-20
      • 2010-12-31
      • 2012-05-31
      相关资源
      最近更新 更多