nodejs+mysql插入一条记录时获取自动生成的id

nodejs+mysql插入一条记录时获取自动生成的id

最近在写添加房源项目的后端接口时发现需要获取数据库自动生成的主键,因为要先将房源信息插入到room表,得到生成的房源ID,再将出租类型ID和房源ID插入到rent_room表

发现,在插入操作完成后的返回结果里就带有自动生成的ID。可用data.insertId获取

const dao = require("../dao/pageDao");
module.exports = {
async addHouse(req,resp){        
        let roomer_num=req.body.roomer_num;
        let id;//房源id
        await dao.getData("insert into t_room(roomer_num) values(?)",[roomer_num]).then(data=>{
            id=data.insertId;//获取自动生成的id
        });

    }
}
const dbConfig = require("../config/dbConfig")
module.exports = {
    getData(sql,arr){
        // 向数据库发起请求
        return new Promise((resolve, reject) => {
            dbConfig.db(sql,arr).then((data)=>{
                resolve(data)
            })
            // resolve("数据库查询结果")
        })
    }
}
const mysqlModule = require("mysql")

module.exports = {
    db(sql,data){
        return new Promise((resolve, reject) => {
            let db = mysqlModule.createConnection({
                host:"45.77.201.2",
                port:3306,
                user:"demo",
                password:"demo",
                database:"demo"
            })
            db.connect()
            db.query(sql,data,function (err, data) {
                if(!err){
                    resolve(data)
                }else {
                    reject(err)
                }
            })
            db.end()
        })

    }
}

你可能感兴趣的:(node,js,mysql,node.js,mysql)