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粉7318612412024-03-20 15:00:01
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 < 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'); } }
Note that I changed genderTypeId='genderTypeId'
to ngenderTypeId='\${genderTypeId}'
in the first SQL query. This should fix the syntax error.