首先,需要理解该错误的产生原因,即在于连接的mysql实例出现了致命错误,后续再进行查询等操作就会出现该错误。
处理该错误的方式如下:
- 在创建连接的时候,加上
supportBigNumbers: true,
与bigNumberStrings: true
配置。
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'user',
password: 'password',
database: 'database',
supportBigNumbers: true,
bigNumberStrings: true
});
connection.connect((err) => {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
- 在进行mysql操作之前,需要验证连接状态,如果连接不正常,需要进行重连。
const mysql = require('mysql');
function handleDisconnect() {
const connection = mysql.createConnection({
host: 'localhost',
user: 'user',
password: 'password',
database: 'database'
});
connection.connect((err) => {
if (err) {
console.error('error connecting: ' + err.stack);
setTimeout(handleDisconnect, 2000);
return;
}
console.log('connected as id ' + connection.threadId);
});
connection.on('error', (err) => {
if (err.code === 'PROTOCOL_CONNECTION_LOST') {
console.error('Database connection was closed.');
handleDisconnect();
} else {
throw err;
}
});
}
handleDisconnect();
示例1:使用第一种方式处理同步查询mysql出现该错误的情况。
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'user',
password: 'password',
database: 'database',
supportBigNumbers: true,
bigNumberStrings: true
});
connection.connect((err) => {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
connection.query('SELECT * FROM users', (error, results, fields) => {
if (error) {
console.log('Error occurred:', error);
return;
}
console.log('Results:', results);
});
});
示例2:使用第二种方式处理同步查询mysql出现该错误的情况。
const mysql = require('mysql');
function handleDisconnect() {
const connection = mysql.createConnection({
host: 'localhost',
user: 'user',
password: 'password',
database: 'database'
});
connection.connect((err) => {
if (err) {
console.error('error connecting: ' + err.stack);
setTimeout(handleDisconnect, 2000);
return;
}
console.log('connected as id ' + connection.threadId);
connection.query('SELECT * FROM users', (error, results, fields) => {
if (error) {
console.log('Error occurred:', error);
return;
}
console.log('Results:', results);
connection.end();
});
});
connection.on('error', (err) => {
if (err.code === 'PROTOCOL_CONNECTION_LOST') {
console.error('Database connection was closed.');
handleDisconnect();
} else {
throw err;
}
});
}
handleDisconnect();
通过以上两种方式,可以避免出现Nodejs连接mysql时报Error: Cannot enqueue Query after fatal error错误,并保证mysql连接正常进行数据操作。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Nodejs 连接 mysql时报Error: Cannot enqueue Query after fatal error错误的处理办法 - Python技术站