node.js - nodejs中,mysql连接——是每次查询连接一次数据库,还是启动node时连接数据库,关闭时再断开好呢?
黄舟
黄舟 2017-04-17 12:08:15
0
2
724
黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(2)
Peter_Zhu

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();
黄舟

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!