Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

1.4K
Visualizações
Too many connections Nodejs + mysql2/promise

I am working in a proyect with nodejs + mysql2 and some times I got the error Too many connections.

My connection:

import {createPool, Pool} from 'mysql2/promise';

export async function connect(): Promise < any > {
  const connection: Pool = await createPool({
    host: 'localhost',
    port: 3306,
    user: 'root',
    password: '',
    database: 'mendozarq',
    connectionLimit: 10
  });
  return connection;
}

Controller:

import { Response, Request } from 'express';
import { FieldPacket, Pool } from 'mysql2/promise';

import { connect } from './../../classes/database';
import { Personal } from './../../models/personal.interface';

export const getAllPersonal = async (req: Request, res: Response) => {
    try {
        const conn: Pool = await connect();

        const [personal]: [any[], FieldPacket[]] = await conn.query('SELECT * FROM personal ORDER BY creadoEn DESC');
        conn.end();

        return res.status(200).json(personal);

    } catch (error) {
        return res.status(400).json({
            error
        });
    }
}

So, my question is I have to use createConnection instead of createPool or I just have to create one instance of my conn.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You should only be calling createPool once, then select from the pool every time thereafter.

So, it should look something like this. Create a constant that stores the pool. Then in the function if the pool already exists return the pool without calling createPool. If it doesn't exist, then you would call createPool and return the already created pool.

import {createPool, Pool} from 'mysql2/promise';

const globalPool: Pool | undefined = undefined;

export async function connect(): Promise <Pool> {

  // If the pool was already created, return it instead of creating a new one.
  if(globalPool) {
    return globalPool;
  }

  // If we have gotten this far, the pool doesn't exist, so lets create one.
  globalPool = await createPool({
    host: 'localhost',
    port: 3306,
    user: 'root',
    password: '',
    database: 'mendozarq',
    connectionLimit: 10
  });
  return globalPool;
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda