我正在使用Node JS,我正在尝试连接到mysql数据库.它因超时而不断断开连接,因此我写了一个函数来重新连接,如果它超时.虽然我需要它是一个连续的连接或我的代码中的引用将无法正常工作.这是我的相关代码:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '.........', // MySQL Host
user : '.........', // MySQL User
password : '.........', // MySQL Password
database : '.........' // MySQL Databse
});
// MYSQL INFO
//connection.connect();
function replaceClientOnDisconnect(connection) {
connection.on("error", function (err) {
if (!err.fatal) {
console.log('Databse Error, error not fatal');
return;
}
if (err.code !== "PROTOCOL_CONNECTION_LOST") {
throw err;
console.log('PROTOCOL_CONNECTION_LOST Error: Reconnecting to database...');
}
setTimeout(function () {
connection.destroy();
connection = mysql.createConnection(connection.config);
replaceClientOnDisconnect(connection);
connection.connect(function (error) { …Run Code Online (Sandbox Code Playgroud)