一、目录
├─ server
│ ├─ app.js
│ ├─ controller
│ │ ├─ account.js
│ ├─ DBhelper
│ │ └─ mysql.js
│ ├─ package-lock.json
│ ├─ package.json
│ └─ routers
│ ├─ account.js
二、封装接口mysql.js
const mysql = require('mysql');
//创建连接池对象
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '密码',
port: '3306',
database: '数据库',
},
//tokenKey: "myUrl.com"
);
pool.on('connection', (connection) => {
//logger.info("connection!");
});
pool.on('enqueue', () => {
//logger.info('Waiting for available connection slot');
});
module.exports.Pool = pool;
module.exports.getConnection = (cb) => {
if (typeof cb == "function") {
pool.getConnection(function (err, connection) {
cb(err, connection);
});
} else {
return new Promise((resolve, reject) => {
pool.getConnection((err, connection) => {
if (err) {
reject(err);
} else {
resolve(connection);
}
});
});
}
};
module.exports.exec = (sql, values, cb) => {
if (typeof cb == "function") {
pool.getConnection((err, connection) => {
if (err) {
connection.release();
cb(err);
} else {
connection.query(sql, values, (error, rows) =&g