学习NodeJS时,遇到Error: Cannot enqueue Handshake after invoking quit.的解决方案

问题


Error: Cannot enqueue Handshake after invoking quit.


在最近学习node.js如何连接mysql数据库时,遇到了一个问题,第一次连接数据库时正常,再次与数据库交互时报错:Error: Cannot enqueue Handshake after invoking quit.

原因就是:当你在发出请求的时候执行connection.connect(),为了不占用连接,每次都会connection.end(),但是下一次请求时,并没有创建新的连接。

最简单的方法是去掉connection.end(),让数据库自己释放不活跃的连接。
如果有强迫症一定要connection.end(),可以试试下面的解决方法:

dbutil.js:

var mysql = require('mysql');

var connection = mysql.createConnection({
    host: '127.0.0.1',
    database: 'school',
    user: 'root',
    password: '123456'
});

module.exports = connection;

dao文件:

var connection = require('./dbutil');

function queryStudentBysNoAndSex(sNo, sex) {
    connection.connect();
    var queryStudent = "select * from student where sNo = ? and sex = ?";
    var params = [sNo, sex];
    connection.query(queryStudent, params, function (error, result) {
        if (error == null) {
            console.log(result);
        } else {
            console.log(error);
        }
        connection.end();
    });
}

经过修改后:

dbutil.js导出模块为createConnection函数:

var mysql = require('mysql');

function createConnection() {
    var connection = mysql.createConnection({
        host: '127.0.0.1',
        database: 'school',
        user: 'root',
        password: '123456'
    });
    return connection;
}
module.exports.createConnection = createConnection;

Dao文件中每次dbutil.createConnection();即可:

var dbutil = require('./dbutil');
var connection = null;

function queryStudentBysNoAndSex(sNo, sex) {
    connection = dbutil.createConnection();
    connection.connect();
    var queryStudent = "select * from student where sNo = ? and sex = ?";
    var params = [sNo, sex];
    connection.query(queryStudent, params, function (error, result) {
        if (error == null) {
            console.log(result);
        } else {
            console.log(error);
        }
        connection.end();
    });
}

这样就可以每次请求时createConnection()方法创建一个新连接,结束后end().

你可能感兴趣的:(前端)