Node Mysql连接池操作封装

之前写了一个对mysql操作的封装的博客:node mysql操作封装

后面方向,当你访问量比较大的时候,直接用mysql的连接是会崩掉的,不支持这么多的连接,用连接池操作比较好,然后就操作了一下

const mysql = require('mysql');

module.exports = {
    config: {
        host: 'localhost',
        port: 3306,
        database: 'glory_of_kings',
        user: 'root',
        password: 'root',
        useConnectionPooling: true // 使用连接池
    },
    pool: null,
    /**
     * 创建连接池
     */
    create: function () {
        const me = this;
        // 没有pool的才创建
        if (!me.pool) {
            me.pool = mysql.createPool(me.config);
        }
    },
    /**
     * 执行sql
     * @param {Object} config 操作对象
     */
    exec: function (config) {
        const me = this;
        me.create();
        me.pool.getConnection((err, conn) => {
            if (err) {
                console.log('mysql pool getConnections err:' + err);
                throw err;
            } else {
                conn.query(config.sql, config.params, (err, result) => {
                    if (config.success) {
                        config.success(result);
                    }
                    if (config.error) {
                        config.error(err)
                    }
                    // 释放连接到连接池
                    conn.release();
                });
            }
        });
    }
};

//test
const handler = require('./mysqlHandler.js');
handler.exec({
    sql: 'select * from table where id = ?',
    params: [id],
    success: res => {
        console.log(res);
    },
    error: err => {
        console.log(err);
    }
});

猜你喜欢

转载自blog.csdn.net/u014264373/article/details/85255136