config.js:
const mysqlConfig = {
host: 'localhost',
port: 3306,
database: 'test',
user: 'root',
password: 'root'
}
module.exports = {
mysqlConfig
}
mysql.js:
const mysqlConfig = require('../config/config.js');
//创建并使用连接池对象
const mysql = require('mysql');
const pool = mysql.createPool(mysqlConfig);
// 封装函数,调用
function doSQL(sql, params = []) {
return new Promise((resolve, reject) => {
pool.getConnection(function (error, connection) {
if (error) {
reject(error)
} else {
connection.query(sql, params, function (err, data, fields) {
connection.release()
resolve({
err,
data,
fields
})
})
}
})
})
}
module.exports = doSQL;