标签:
两种方式解决
1、你可以配置mysql的连接池
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、你可以使用断线重连的方式来解决
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();
标签:
原文地址:http://www.cnblogs.com/youlechang123/p/4858248.html