You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Node.js(Express框架)中获取最后插入的ID?

如何正确获取MySQL最后插入的ID(Node.js + Express)

你的代码存在几个关键问题,导致无法正确获取最后插入的ID,以下是修复方案:

问题梳理

  1. 函数参数为salonId,但SQL语句中误用了未定义的shopId,会引发变量未定义错误
  2. 判断数据是否存在时,直接用rows<1错误,rows是查询结果数组,需用rows.length < 1
  3. SQL语句采用字符串拼接,存在SQL注入风险,且genderTypeId='genderTypeId'是硬编码字符串,未正确引用变量
  4. pool.execute返回的是包含结果对象和字段信息的数组,直接访问datass.insertId会得到undefined

修复后的代码

static async addServiceDetail(salonId, serviceId, genderTypeId, price, serviceName) {
    // 注意:这里将参数salonId映射为shopId,若数据库字段是salonId,需同步修改SQL中的字段名
    const shopId = salonId;
    // 使用参数化查询避免注入,同时修正变量引用
    const sql = `SELECT id from hc_servicesdetail WHERE shopId=? AND serviceId=? AND genderTypeId=?`;
    const [rows] = await pool.execute(sql, [shopId, serviceId, genderTypeId]);
    
    if (rows.length < 1) {
        const sql2 = `INSERT INTO hc_servicesdetail (shopId, serviceId, genderTypeId, price, serviceName) VALUES (?, ?, ?, ?, ?)`;
        // 解构获取执行结果对象
        const [result] = await pool.execute(sql2, [shopId, serviceId, genderTypeId, price, serviceName]);
        console.log('last inserted id is ' + result.insertId);
        return result.insertId; // 可返回ID供调用方使用
    } else {
        console.log('already exist');
        return null;
    }   
}

module.exports = User;

关键说明

  • 使用参数化查询(?作为占位符)替代字符串拼接,既避免SQL注入,也能正确传递变量
  • pool.execute执行后返回[result, fields],解构出result对象后,result.insertId就是最后插入的自增ID
  • 修正了变量不匹配的问题,确保函数参数与SQL中的变量/字段对应

内容的提问来源于stack exchange,提问作者Diana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 09:02:54