config.js:

    1. const mysqlConfig = {
    2. host: 'localhost',
    3. port: 3306,
    4. database: 'test',
    5. user: 'root',
    6. password: 'root'
    7. }
    8. module.exports = {
    9. mysqlConfig
    10. }

    mysql.js:

    1. const mysqlConfig = require('../config/config.js');
    2. //创建并使用连接池对象
    3. const mysql = require('mysql');
    4. const pool = mysql.createPool(mysqlConfig);
    5. // 封装函数,调用
    6. function doSQL(sql, params = []) {
    7. return new Promise((resolve, reject) => {
    8. pool.getConnection(function (error, connection) {
    9. if (error) {
    10. reject(error)
    11. } else {
    12. connection.query(sql, params, function (err, data, fields) {
    13. connection.release()
    14. resolve({
    15. err,
    16. data,
    17. fields
    18. })
    19. })
    20. }
    21. })
    22. })
    23. }
    24. module.exports = doSQL;