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

320
Visualizações
How to write a common MySQL query which will return result when called from API function in NodeJS?

Right now whenever I want to execute a mysql query in my api functions I create a DB connection , then executing the query and releasing the connection for each api function. The code gets messier when nested DB query should be executed and Even I thought about performance issues since connections are continuously created and released . This is my current implementation

dbServer.js

const db = mysql.createPool({
   connectionLimit: 100,
   host: DB_HOST,
   user: DB_USER,
   password: DB_PASSWORD,
   database: DB_DATABASE,
   port: DB_PORT
})

module.exports = db

app.js (main file)

const express = require("express")
const app = express()
app.use(express.json())
const db = require('./dbServer')

require('./Backend/Routes/ApifileName')(app , db);

const port = process.env.PORT

app.listen(port)

ApiFileName.js

const mysql = require("mysql")
const auth = require("../Middlewares/VerifyMerchantAuth")

module.exports = function(app , db){
    app.post("/v1/route" ,auth, async(req , res) => {

        let someParam= req.body.someParam;

        let sql_command = "SELECT * from table_Name where column_name = ?"
        let sql_query   = mysql.format(sql_command,[someParam])

        db.getConnection ( async (err, connection)=> {
            if (err) throw err;

            await connection.query (sql_query, async (err, result) => {
                connection.release();

                if (err) throw err;

                if(result.length == 0){
                    return res.json({error : "some error"})
                }

                return res.json({result : "some result"});
            })
        })
    })
} 

My Files Hierarchy

node_modules
package.json
app.js
dbServer.js
Backend -> 1. Routes -> ApiFileName.js
           2. Middlewares -> Here I want to write this sql function

My requirement now is I need to write a common function which takes db and sql_query as parameters and should return response if success or error.

I tried it myself but the mysql response comes after the api returns it's response. I tried using await , .then() but nothing worked.

Or Is this current implemented method is efficient already? Give your views.

Please Help me and Thanks in advance

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

A new connection for each SQL query is terrible for performance. Have a single connection for the entire invocation of the app. That may involve having a "global" or "static" place to hold the "handle" to the connection.

If you are in a web environment, you cannot keep the connection from one "web page" to the next. Simply let it go and connect again on the next page.

Don't worry about "pools"; they done buy enough performance to worry about.

There is a rare case where you need more than one "connection" in an app -- if you are talking to different servers. Within a single server, one connection can interact with all the databases and tables (that it has permission to touch).

about 4 years ago · Juan Pablo Isaza 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