noddy asked this 7 years ago

NodeJS Cannot enqueue Handshake after already enqueuing a Handshake

I am trying to insert into MYSQL table some data recieved from AJAX post.

Error: Cannot enqueue Handshake after already enqueuing a Handshake.

    at Protocol._validateEnqueue (C:\nodejs\node_modules\mysql\lib\protocol\Protocol.js:208:16)

    at Protocol._enqueue (C:\nodejs\node_modules\mysql\lib\protocol\Protocol.js:135:13)

    at Protocol.handshake (C:\nodejs\node_modules\mysql\lib\protocol\Protocol.js:52:41)

    at Connection.connect (C:\nodejs\node_modules\mysql\lib\Connection.js:136:18)

    at C:\nodejs\myindex.js:28:13

    at Layer.handle [as handle_request] (C:\nodejs\node_modules\express\lib\router\layer.js:95:5)

    at next (C:\nodejs\node_modules\express\lib\router\route.js:131:13)

    at Route.dispatch (C:\nodejs\node_modules\express\lib\router\route.js:112:3)

    at Layer.handle [as handle_request] (C:\nodejs\node_modules\express\lib\router\layer.js:95:5)

    at C:\nodejs\node_modules\express\lib\router\index.js:277:22

 

 

The code I am using is

var mysql = require('mysql')
var connection = mysql.createConnection({
  host: 'localhost',
  user: 'myusername',
  password: 'mypassword'
})

function insertData(name,id) {

  connection.connect();

  console.log(name+' '+age)
  connection.query('INSERT INTO members (name, id) VALUES (?, ?)', [name,id], function(err,result) {
	  if(err) throw err
  });

  connection.end();


}

app.post('/', function(req, res) {
	
	insertData(req.body.name,req.body.id);
        //Rest of the code

});

 


sonja 7 years ago
10 likes

Do not connect() and end() inside the function. This will cause problems on repeated calls to the function. Make the connection only

var connection = mysql.createConnection({
	  host: 'localhost',
	  user: 'node',
	  password: 'node',
	  database: 'node_project'
	})

connection.connect(function(err) {
	if (err) throw err
	
});

once and reuse that connection.

 

Inside the function 

function insertData(name,id) {

  connection.query('INSERT INTO members (name, id) VALUES (?, ?)', [name,id], function(err,result) {
	  if(err) throw err
  });


}
Guest 5 years ago
5 likes

Here I have a simple class for MySQL connection and query

class DatabaseMySQL {
	constructor(db) {
	  const stringConexaoDB = {host:'localhost', user:'root', password:'123456', database:db}
	  this.connection = mysql.createConnection(stringConexaoDB);
	  console.log('Conectado ao Banco', db); 
	}
	
	query(sql, args) { 
		return new Promise((resolve, reject) => { 
		  this.connection.query(sql, args, (err, rows) => {
		    if (err) return reject(err);
		    resolve(rows);
		  })
		})
	}
	
	module.exports = DatabaseMySQL;
	
	 ****** I have a funExec () function; *********
	
	function funExec()  {
	  db.query('SELECT * FROM DB_ICADIS.CLIENTE ORDER BY cli_codigo')
	    .then(rows => {
	      rows.forEach((row) => {
	        funRegistroCli(row);
	      })
	      db.close();
	    })
	   .catch((error) => {
	   	console.log(error)
	   	db.close();
	   })

***********************************************
When I run the function Wheel normally and after the execution of the rows, closes the connection everything ok!

NOW WHEN I EXECUTE WITHIN A ROUTE EXPRESS AS BELOW:

***********************************************

rotaCliente.get('/cliente', async (req, res, next) => { 
	await funExec(); 
	res.json({ola:"terminei"})
})

For not having closed the bank, when having the second time, gives the following error:

Guest 4 years ago
2 likes

Had the same problem and found the decisive solution here.

First I had set con.connect() also within the function. But according to Sonja this does not belong into the function or leads to problems. So I executed it outside the function. This worked quite well, but was not sufficient for me yet. On my SharedServer there are processes with a runtime limited 180/300 seconds. Then the script aborts because there is still a connection to the database. What now?
So I implemented a function handleSql and declare the variable con. At the end I end the connection with con.end()

function handleSql(mode,callback){
	var con = mySql.createConnection({
	   host:'xxxxxxxxxx',
	   user:'xxxxxxxxxxx',
	   password:'xxxxxxxxxxxx',
	   database:'xxxxxxxxxxx'
	 });
	con.connect(function(err){
	 if(err) throw err;
	});
	var sql = 'SELECT * FROM content';
	con.query(sql,function(err,result,fields){
	  if(err) throw err;
	  if(callback) callback(err,result,fields);
	}); 
	con.end();
};