Nodejs: Retrieve last inserted ID
P粉463824410
P粉463824410 2024-03-19 22:36:08
0
1
336

I am using Nodejs and using expressjs framework and now I am trying to get "Last inserted id" but I am getting "undefined" in the console, how can I get the last inserted id? This is my current code

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粉463824410
P粉463824410

reply all(1)
P粉731861241

Use the result.insertId property. This property is available in the callback function that is executed when the INSERT query is executed.

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 

Note that I changed genderTypeId='genderTypeId' to ngenderTypeId='\${genderTypeId}' in the first SQL query. This should fix the syntax error.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template