一段时间后,在节点js中关闭了Mysql连接,并给出了PROTOCOL_CONNECTION_LOST'

时间:2017-11-20 11:01:02

标签: mysql node.js

我是节点mysql的新手,我遇到了一个问题。
我的节点js服务器关闭,连接关闭PROTOCOL_CONNECTION_LOST。
我不明白我哪里出错了。如果有人知道,请解决。
提前致谢

var sockjs = require('sockjs');
var mysql = require('mysql');

var connection = mysql.createConnection({
  host     : process.env.IP,
  user     : 'root',
  port     : '80',
  password : '123456',
  database : 'test',
});

connection.connect(function(err) {
    if(err){
        console.log('error in connection is : ',err);
    }else{
        console.log("Connected!");
    }
});

var echo = sockjs.createServer();
var connections = [];


echo.on('connection', function (conn) {
    connections.push(conn);
    conn.on('data', function (message) {        

        var sql1 = "SELECT count(`id`) as counting FROM `complaints_chat` WHERE `createby`='client' and `read`='0'";
        connection.query(sql1, function(err, rows, fields) {
            if (err) throw err;
            if (rows.length > 0) {
                counting=rows[0]['counting'];
            }else{ counting=0; }  
        });
    });
});

1 个答案:

答案 0 :(得分:0)

您可以在断开连接时恢复连接,例如

connection.on('error', err => {
        if (err.code === 'PROTOCOL_CONNECTION_LOST') {
            // db error reconnect
            disconnect_handler();
        } else {
            throw err;
        }
    });