1

I am using node.js and mysql, to run sql commands frequently.

I am getting this error: Cannot enqueue Handshake after invoking quit.

This is when I do

connection = mysql.createConnection(sqlDetails);
connection.connect();

and

connection.end();

If I comment the .connect and .end lines, then I get the error ER_CON_COUNT_ERROR: Too many connections.

Does anyone know how to fix this problem?

Thanks

omega
  • 40,311
  • 81
  • 251
  • 474
  • have you seen this: http://stackoverflow.com/questions/14087924/cannot-enqueue-handshake-after-invoking-quit – knowbody Apr 27 '14 at 20:34
  • According to this https://github.com/felixge/node-mysql#error-handling, it says to define your connection one, then just use that always. I did that, but now I'm not sure where to put my `connection.end()`. It says `You can listen on the error event to handle server disconnection and for reconnecting purposes.` but im not sure which function to put it in... – omega Apr 27 '14 at 20:43
  • you should close one global connection the first request done, do not use a connection pool and grab a connection for each request separately or dont close the connection in the request handlers – knowbody Apr 27 '14 at 20:48

2 Answers2

2

If you actually want to close connection (why? if you 'run sql commands frequently' you probably want to reuse it, or even better - use connection pool) you need to do that in query result callback. All commands are put into commands queue and processed sequentially.

This is what you are doing:

  • open connection stream to mysql
  • add Handshake command to queue
  • add Query command to queue
  • add Quit command to queue, mark connection as closing
  • start processing commands
  • now Handshake is processed when connection in 'closing' state
Andrey Sidorov
  • 24,905
  • 4
  • 62
  • 75
2

Since node js is asynchronous , connection.connect() and connection.end() gets executed parallely,

If you want to specify sequence of execution, use callbacks like

connection = mysql.createConnection(sqlDetails);
connection.connect(function(err,callback){
    connection.query(function(err,callback){
         connection.end();
 });
});
keerthee
  • 812
  • 4
  • 17
  • 39