Heim > Fragen und Antworten > Hauptteil
Ich verwende Nodejs und das ExpressJS-Framework und versuche es jetzt zu bekommen „Zuletzt eingefügte ID“, aber in der Konsole wird „undefiniert“ angezeigt. Wie kann ich die zuletzt eingefügte ID abrufen? Das ist mein aktueller 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
使用 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}'
。这应该修复语法错误。