何时使用node-mysqlclosuresMySQL连接?

目前使用: https : //github.com/felixge/node-mysql

我有以下代码:

var connection = mysql.createConnection({ host : 'localhost', user : 'me', password : 'secret', database : 'Database1' }); app.put('/api/upload', function(req, res, next) { connection.connect(); doMultipleQueries(function(err) { connection.end(); }); }; 

放置请求工作得很好,但第二次调用它,我得到以下错误

 events.js:68 throw arguments[1]; // Unhandled 'error' event ^ Error: Cannot enqueue Handshake after invoking quit. at Protocol._validateEnqueue (/Users/anon/Desktop/project Web/node_modules/mysql/lib/protocol/Protocol.js:110:16) 

我应该离开连接,直到服务器死亡?

更新:当我将mysql.createConnection移入放置请求函数如下所示:

 var connection = null; app.put('/api/upload', function(req, res, next) { connection = mysql.createConnection({ host : 'localhost', user : 'me', password : 'secret', database : 'Database1' }); connection.connect(); doMultipleQueries(function(err) { connection.end(); }); }; 

它工作正常。 这是否意味着connection.end()closures什么mysql.createConnection创build,不能重新连接?

如果在COM_QUIT包发送之前发生了一个致命错误,那么connection.end()就会执行这个工作,这个错误将被提供给callback函数,但是连接将被终止。

还要检查destroy()方法 。 这将导致底层套接字的立即终止。

您可以添加error handling程序。

https://github.com/felixge/node-mysql/blob/master/Readme.md#error-handling

 connection.on('error', function() {}); 

一旦终止,现有的连接对象不能通过devise重新连接。

在这里检查。 断开连接后显示连接。

https://github.com/felixge/node-mysql/blob/master/Readme.md#server-disconnects

我相信正确的方法是在启动时为您的应用程序build立连接,并在应用程序closures时end()