搜索

首页  >  问答  >  正文

Nodejs:检索最后插入的 ID

我正在使用 Nodejs 并使用expressjs框架,现在我正在尝试获取 “最后插入的 id”,但我在控制台中收到“未定义”,如何获取最后插入的 id?这是我当前的代码

static async addServiceDetail(salonId,serviceId,genderTypeId,price,serviceName)
    {
        const sql = `SELECT id from hc_servicesdetail WHERE shopId='${shopId}' AND  serviceId='${serviceId}' AND genderTypeId='genderTypeId'`;
        const [rows, fields] = await pool.execute(sql);
        if(rows<1)
            {
                const sql2 = `INSERT INTO hc_servicesdetail (shopId, serviceId, genderTypeId,price,serviceName) VALUES ("${shopId}", "${serviceId}", "${genderTypeId}", "${price}","${serviceName}")`;
                const datass = await pool.execute(sql2);
                console.log('last inserted id is ' +datass.insertId);
            }
        else
            {
                console.log('already exist');
            }   
    }
}

module.exports = User;

P粉463824410P粉463824410256 天前339

全部回复(1)我来回复

  • P粉731861241

    P粉7318612412024-03-20 15:00:01

    使用 result.insertId 属性。此属性在执行 INSERT 查询时执行的回调函数中可用。

    static async addServiceDetail(shopId, serviceId, genderTypeId, price, serviceName) {
        const sql = `SELECT id from hc_servicesdetail WHERE shopId='${shopId}' AND  serviceId='${serviceId}' AND genderTypeId='${genderTypeId}'`;
        const [rows, fields] = await pool.execute(sql);
        if (rows < 1) {
            const sql2 = `INSERT INTO hc_servicesdetail (shopId, serviceId, genderTypeId, price, serviceName) VALUES ("${shopId}", "${serviceId}", "${genderTypeId}", "${price}","${serviceName}")`;
            const [datass, _] = await pool.execute(sql2);
            console.log('last inserted id is ' + datass.insertId);
        } else {
            console.log('already exist');
        }
    }

    请注意,我在第一个 SQL 查询中将 genderTypeId='genderTypeId' 更改为 ngenderTypeId='\${genderTypeId}' 。这应该修复语法错误。

    回复
    0
  • 取消回复