Home  >  Q&A  >  body text

node.js - nodejs中,mysql连接——是每次查询连接一次数据库,还是启动node时连接数据库,关闭时再断开好呢?

黄舟黄舟2743 days ago725

reply all(2)I'll reply

  • 天蓬老师

    天蓬老师2017-04-17 12:10:15

    Two ways to solve it
    1. You can configure the mysql connection pool

    var mysql = require('mysql');
    var pool = mysql.createPool({
        host: 'localhost',
        user: 'nodejs',
        password: 'nodejs',
        database: 'nodejs',
        port: 3306
    });
    
    var selectSQL = 'select * from t_user limit 10';
    
    pool.getConnection(function (err, conn) {
        if (err) console.log("POOL ==> " + err);
    
        conn.query(selectSQL,function(err,rows){
            if (err) console.log(err);
            console.log("SELECT ==> ");
            for (var i in rows) {
                console.log(rows[i]);
            }
            conn.release();
        });
    });
    

    2. You can solve the problem by disconnecting and reconnecting

    var mysql = require('mysql');
    var conn;
    function handleError () {
        conn = mysql.createConnection({
            host: 'localhost',
            user: 'nodejs',
            password: 'nodejs',
            database: 'nodejs',
            port: 3306
        });
    
        //连接错误,2秒重试
        conn.connect(function (err) {
            if (err) {
                console.log('error when connecting to db:', err);
                setTimeout(handleError , 2000);
            }
        });
    
        conn.on('error', function (err) {
            console.log('db error', err);
            // 如果是连接断开,自动重新连接
            if (err.code === 'PROTOCOL_CONNECTION_LOST') {
                handleError();
            } else {
                throw err;
            }
        });
    }
    handleError();
    

    reply
    0
  • 黄舟

    黄舟2017-04-17 12:10:15

    Mysql has a connection pool. When concurrency is large, if your previous connection is not closed, the connection pool is full, the request cannot be processed, and the program will block, so it needs to be released when it is used up

    reply
    0
  • Cancelreply