Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

283
Vistas
How to return data from SQL with Node.js (mysql2)

I rewrite my code from Python to Node.js I need to get some data from SQL and then use it in the code after. So it is easy with python, you just get it, return and you can use it.

The code in Python

def sql_get_new_id(connection):

    with connection.cursor() as cursor:

    sql = "SELECT * FROM `item` WHERE 1"
    cursor.execute(sql)
    result = cursor.fetchall()

    return len(result)  # <==== So you just can get this data and use it out of the loop
 
print(sql_get_new_id()) # <==== Right here it works perfectly

But in JS as i see i cant just get it with return at the end of the function. You can only see it at the console. So how do i get it now?

const mysql = require("mysql2");
 
const sql = `SELECT * FROM item WHERE 1`;
 
connection.query(sql, function(err, results) {
    if(err) console.log(err);
    console.log(results.length);  // <===== I can do a console log
    return results.length;  // <====== But returning doesn't let me use it out of the loop
});
 
connection.end();
}

console.log(sqlGetNewId())  // <==== There is no data i need
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

In the function instead of console log you can put: return results.lengtg;

If that's what you wanted to do

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda