Nodejs?连接?mysql时报Error:?Cannot?enqueue?Query?after?fatal?error错误的处理办法(nodejs怎么连接mysql)没想到
//导入mysql连接包
const mysql=require(‘mysql’);
let dbconfig={
host: ‘db_host’,
user: ‘db_user’,
password: ‘db_pass’,
database: ‘db_name’,
debug: true
};
function handleDisconnection() {
db=mysql.createConnection(dbconfig);
db.connect(function (err) {
if (err) {
console.log(‘db connect error:’ + err.message + “2秒后重连”);
setTimeout(handleDisconnection, 2000);
}
});
db.on(‘error’, function (err) {
console.log(err);
if (err.code===’PROTOCOL_CONNECTION_LOST’) {
console.log(‘db error执行重连:’ + err.message);
handleDisconnection();
} else {
throw err;
}
});
db.querySync=function(sql) {
return new Promise(function(resolve, reject) {
db.query(sql, function(error, results, fields) {
if(error) reject(error);
else resolve({results, fields})
})
})
};
return db;
}
//创建连接conn
exports.db=handleDisconnection();
const mysql=require(‘mysql’);
let dbconfig={
host: ‘db_host’,
user: ‘db_user’,
password: ‘db_pass’,
database: ‘db_name’,
debug: true
};
function handleDisconnection() {
db=mysql.createConnection(dbconfig);
db.connect(function (err) {
if (err) {
console.log(‘db connect error:’ + err.message + “2秒后重连”);
setTimeout(handleDisconnection, 2000);
}
});
db.on(‘error’, function (err) {
console.log(err);
if (err.code===’PROTOCOL_CONNECTION_LOST’) {
console.log(‘db error执行重连:’ + err.message);
handleDisconnection();
} else {
throw err;
}
});
db.querySync=function(sql) {
return new Promise(function(resolve, reject) {
db.query(sql, function(error, results, fields) {
if(error) reject(error);
else resolve({results, fields})
})
})
};
return db;
}
//创建连接conn
exports.db=handleDisconnection();
© 版权声明
文章版权归作者所有,未经允许请勿转载。