使用Mysql检索最后插入的id

问题描述 投票:0回答:4

美好的一天,

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

我知道有 mysqli_insert_id 函数,但是:

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

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

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

mysql node.js
4个回答
179
投票

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

12
投票
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


0
投票

const 查询 = '插入礼品卡(卡号、卡余额、卡到期日期、收件人电子邮件、商店 ID、客户 ID)值 (?,?,?,?,?,?)';

常量值 = [卡号、卡余额、卡到期日期、收件人电子邮件、商店 ID、客户 ID];

            const [results] = await db.execute(query, values);

            const lastInsertId = results.insertId;

            console.log('Last Inserted ID:', lastInsertId);

-2
投票

我认为您误解了

mysqli_insert_id()
方法的使用。该方法必须在插入语句之后立即执行,以获得最后插入的id。如果你直接用我的 MySQL 来完成

INSERT INTO(a,b)values(1,'test');
SELECT LAST_INSERT_ID();  -- this will display the last inserted id
© www.soinside.com 2019 - 2024. All rights reserved.