何时使用node-mysql关闭MySQL连接? [英] When to close MySQL connection using node-mysql?

查看:555
本文介绍了何时使用node-mysql关闭MySQL连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前正在使用: 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();
    });          
};

put请求完全正常,但第二次调用它,我收到以下错误

The put request works perfectly fine, but calling it the second time, I get the following error

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)



<我是否应该打开连接,直到服务器终止?

Am I supposed to leave the connection open until the server dies?

更新:
当我移动 mysql.createConnection 进入put请求函数,如下所示:

UPDATE: When I move the mysql.createConnection into the put request function like so:

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()关闭创建的 mysql.createConnection 并且无法重新连接?

It works fine. Does this mean connection.end() closes what mysql.createConnection created and cannot be reconnected?

推荐答案

connection.end()无论致命错误如何都能正常工作。如果在可以发送 COM_QUIT 数据包之前发生致命错误,则会向回调提供错误参数,但是无论如何,连接都将终止。

connection.end() does it job regardless to fatal error. If a fatal error occurs before the COM_QUIT packet can be sent, an err argument will be provided to the callback, but the connection will be terminated regardless of that.

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

Also check destroy() method. This will cause an immediate termination of the underlying socket.

您可以添加错误处理程序。

You can add error handler.

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

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






一旦终止,现有的连接对象就无法重新获得按设计连接。


Once terminated, an existing connection object cannot be re-connected by design.

点击此处。它显示断开后连接回来。

Check here. It's showing connecting back after disconnect.

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

这篇关于何时使用node-mysql关闭MySQL连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆