node.js mysql 使用总结

npm install mysql

使用mysql连接池

let mysql = require('mysql');

let db_config = {
    "connectionLimit": 20, //20个连接池
    "host": "x.x.x.x",
    "port": "3306",
    "user": "root",
    "password": "xxxx",
    "database": "xxxxx"
}

let pools;

//使用数据库连接池  回调函数
function mysqlPools(...args) {
    if (pools == null) {
        pools = mysql.createPool(db_config);
    }
    let data = args[1] || [];
    return new Promise((resolve, reject) => {
        pools.query(args[0], data, function (error, results, fields) {
            if (error) reject(error)
            resolve(results)
        });

    })
}


exports.query = mysqlPools;

example1:插入数据

let compileObj = {
   templateId: template.templateId,
   resourceId: body.resourceId,
   targetUrl: body.targetUrl
}
let mrlt = await mysql.query('insert into compile_list set ?', compileObj); //如果使用自动增量主键将一行插入到表中,返回对象中的insertId,是插入行Id

example2:更新数据

 await mysql.query('update compile_list set completed=1,endTime=? where id=?', [new Date(), mrlt.insertId]);

猜你喜欢

转载自www.cnblogs.com/xbblogs/p/9072569.html