简体   繁体   中英

Node.js MySQL query can't assign MySQL results to a variable

I am trying to assign MySQL query results in to a variable and then use it multiple times in script. I want to do this because I have PHP background and I like to work in this way. I know Node.js works asynchronously so this is my problem.

In the code below I want to assign MySQL results in to sql_results variable but connection.query function works asynchronously and code works in different order. In this case at the end of my code when I console.log(sql_results) It returns me undefined . This is normal because when I check console outputs I clearly see console.log(sql_results) worked before console.log(results) .

var mysql = require('mysql');

var connection = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "1234",
  database: "db_progress"
});

var sql_query = "SELECT * FROM db_progress.tblresults res WHERE res.id < 3";
var sql_results; // This is my variable

connection.connect();

connection.query(sql_query, function (error, results, fields) {
  if (error) throw error;
  console.log(results); // This is mysql results
  sql_results = results; // I am sure this works but I can't see
});

connection.end();

console.log(sql_results); // This returns undefined because works before query

How can I assign MySQL results in a variable, or If there is a different method for this purpose. Please explain in details.

Thanks.

Node js function works asynchronously so it's my suggestion to use your query with promise.

class Database {
            constructor( config ) {
                this.connection = mysql.createConnection( config );
            }
            query( sql, args ) {
                return new Promise( ( resolve, reject ) => {
                    this.connection.query( sql, args, ( err, rows ) => {
                        if ( err )
                            return reject( err );
                        resolve( rows );
                    } );
                } );
            }
            close() {
                return new Promise( ( resolve, reject ) => {
                    this.connection.end( err => {
                        if ( err )
                            return reject( err );
                        resolve();
                    } );
                } );
            }
        }

Might try replacing this code,

connection.query(sql_query, function (error, results, fields) {
  if (error) throw error;
  console.log(results); // This is mysql results
  sql_results = results; // I am sure this works but I can't see
});

connection.end();

with this,

connection.query(sql_query)
    .then( results=> {
        sql_results = results;
        return connection.close();
    } );

Danmoreng has already mentioned the articles about Promises and async/await . They will help you understand how the above code works.

The results of your query are returned in a callback function, which executes at a later time than the calling code. You are logging the results in the context of the calling code, before sql_results has been set.

Try this:

var mysql = require('mysql');

var connection = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "1234",
  database: "db_progress"
});

var sql_query = "SELECT * FROM db_progress.tblresults res WHERE res.id < 3";
var sql_results; // This is my variable

connection.connect();

connection.query(sql_query, function (error, results, fields) {
  if (error) throw error;
  console.log(results); // This is mysql results
  sql_results = results; // I am sure this works but I can't see
  console.log(sql_results);
});

connection.end();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM