引入mysql模块 设置全局pool
let mysql = require('mysql');let pool = global.pool;复制代码
创建链接池
if (!pool) { //创建连接池 pool = mysql.createPool({ // host: '101.132.47.132', host: '101.132.47.132', database: 'Bibased', user: 'root', password: 'root' }); //将连接挂载到global global.pool = pool;}复制代码
获取连接池链接
//获取链接function getConnection() { return new Promise(function (resolve, reject) { pool.getConnection(function (err, conn) { if (!err) { resolve(conn); } else { reject(err); } }); })}复制代码
执行数据库操作sql返回sql数据
//执行sqlfunction execute(sql) { return new Promise(function (resolve, reject) { var connection; getConnection().then(function (conn) { connection = conn; conn.query(sql, function (err, result) { if (!err) { resolve(result) } else { reject(err) } }); }).catch(function (err) { reject(err) }).finally(function () { if (connection) { connection.release(); } }); });}复制代码
返回当前模块数据
module.exports = { getConnection, execute};复制代码