Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

279
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!