Gustavo Gil
Gustavo Gil

Reputation: 129

When to close a MySQL connection in Node.js

I am developing an application in Node.js with Express and MySQL. I have the following question, where I should close the connection to MySQL with the following code.

    iniciarSesion(correo_electronico, contrasena, ip){

        return new Promise((resolve, reject) => {
            this.db.query('CALL sp_iniciar_sesion( ?, ?, ?, @o_persona_id, @o_usuario_id, @o_nombre, @o_apellido, @o_privilegio, @o_estado, @o_mensaje)', [correo_electronico, contrasena, ip], (error, results, fields) => {
                if(error)
                    reject();
                else{
                    this.db.query('SELECT  @o_persona_id AS persona_id, @o_usuario_id AS usuario_id, @o_nombre AS nombre, @o_apellido AS apellido, @o_privilegio AS privilegio, @o_estado AS estado, @o_mensaje AS mensaje', (error, results, fields) => {
                        var resultadoFinal = JSON.parse(JSON.stringify(results));
                        if(resultadoFinal[0].estado === 0 || !resultadoFinal[0].estado)
                            reject();
                        else
                            resolve(resultadoFinal); 
                    });
                }
            });
        });
    }

In addition to this, this application is oriented to a large number of people using it at the same time, suppose that 1000 people at a time. Is there a way to optimize the code? or any suggestion?

Thank you.

Update

After a while I get the following error and the application closes:

Error: read ECONNRESET
   at TCP.onStreamRead (internal/stream_base_commons.js:205:27)
Emitted 'error' event on Connection instance at:
   at Connection._handleProtocolError (/home/opencloud/sevenpickup/node_modules/mysql/lib/Connection.js:423:8)
   at Protocol.emit (events.js:310:20)
   at Protocol._delegateError (/home/opencloud/sevenpickup/node_modules/mysql/lib/protocol/Protocol.js:398:10)
   at Protocol.handleNetworkError (/home/opencloud/sevenpickup/node_modules/mysql/lib/protocol/Protocol.js:371:10)
   at Connection._handleNetworkError (/home/opencloud/sevenpickup/node_modules/mysql/lib/Connection.js:418:18)
   at Socket.emit (events.js:310:20)
   at emitErrorNT (internal/streams/destroy.js:92:8)
   at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
   at processTicksAndRejections (internal/process/task_queues.js:84:21) {
 errno: 'ECONNRESET',
 code: 'ECONNRESET',
 syscall: 'read',
 fatal: true
}

Upvotes: 0

Views: 394

Answers (1)

chrispytoes
chrispytoes

Reputation: 1907

Normally, you should just open the connection once upon starting the application. This way you don't have to spend the extra time to reconnect for each query you make.

What you have now looks fine and you do not need to close the connection at all.

Upvotes: 1

Related Questions