我正在使用 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粉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}'
。這應該會修復語法錯誤。