编写mysql的config配置
{
connectionLimit: 2,//连接数限制
host: 'localhost',//数据库host
user: 'root',//用户名
password: 'root',//密码
database: 'db',//数据库
debug: false,//是否开启调试
multipleStatements: true//是否允许同时执行多条语句
}
使用连接池创建一个mysql连接的单例
const mysql = require('mysql');
let conn = undefined;
/**
* 数据库连接
*/
class Connection {
/**
* 构造函数
* @param {Object} config
*/
constructor(config) {
this.config = config;
}
/**
* 获取连接池
* @return {Promise}
*/
getPools() {
let pool = mysql.createPool({
connectionLimit: this.config.connectionLimit,
host: this.config.host,
user: this.config.user,
password: this.config.password,
database: this.config.database,
debug: this.config.debug,
multipleStatements: this.config.multipleStatements
});
return pool;
}
}
//此处暴露出一个连接池单例
module.exports = function(config) {
if (!conn) {
conn = new Connection(config).getPools();
}
return conn;
};
note:连接池不能使用事务,所以如果需要使用事务,需要通过连接池取得一个连接,通过这个连接使用事务,事务开始到结束必须使用同一个连接。
使用连接池获取连接
//Promise写法
return new Promise((resolve, reject)=>{
pool.getConnection((err, conn)=>{
if (err) {
return reject(err);
}
resolve(conn);
});
});