Tag Archives: node.js operation mysql

Node.js operation mysql error Cannot enqueue Handshake after invoking quit

Error Background:
When the database operation is performed for the first time, it is successful. The second time a database operation is performed, an error is reported as shown in the title.
The reason:
This is because after we close the connection with the.end() method, we need to re-call createConnection to recreate a connection.
Solutions:
For example, the following encapsulates a method that operates on database queries and additions. Each time a new connection is created using mysql.createconnection () before the database operation is performed, instead of putting it directly to the outermost layer.

var mysql  = require('mysql');  
exports.find=function(findSql,callback){
    var connection = mysql.createConnection({     
        host     : 'localhost',       
        user     : 'root',              
        password : '123456', 
        port: '3306',                   
        database: 'namesharing',
    });
    connection.connect();
    connection.query(findSql,function (err, result) {
        if(err){
          console.log('[SELECT ERROR] - ',err.message);
          return;
        }
        connection.end();
        callback(result)
    });
}


exports.insert=function(addSql,addSqlParams,callback){
    var connection = mysql.createConnection({     
        host     : 'localhost',       
        user     : 'root',              
        password : '123456',       
        port: '3306',                   
        database: 'namesharing',
    });
    connection.connect();
    connection.query(addSql,addSqlParams,function (err, result) {
        if(err){
            console.log('[INSERT ERROR] - ',err.message);
            return;
        }
        connection.end();
        // console.log('INSERT ID:',result);  
        callback(result)
    });
}