搜尋

首頁  >  問答  >  主體

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粉463824410300 天前364

全部回覆(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
  • 取消回覆