Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the results from nodejs using mysql package?

Tags:

node.js

mysql

first, i connect the db and select DB:

var defaultOptions = {
    user: "root",
    pwd:'admin',
    db:"britcham_dev_local",
    server:"local", // Maybe we don't need this variable.
};

var client = new Client();
client.user = defaultOptions.user;
client.password = defaultOptions.pwd;
client.connect(function (error, results) {
   // 
});
client.query('USE ' + defaultOptions.db, function (error, results) {
   // 
});

Second, I query with client object:

var self = this;
var this.users;
client.query("SELECT * FROM users", function (error, results, fields) {
    if (error) {
        //
    }
    if (results.length  > 0) {
        self.users = results;
    }
});

console.log(this.users);

it's nothing output ??? Why ??

like image 668
user748759 Avatar asked May 11 '11 13:05

user748759


1 Answers

Since node.js is non-blocking and asynchronous, then in this code:

client.query("SELECT * FROM users", function (error, results, fields) {
    if (error) {
        //
    }
    if (results.length  > 0) {
        self.users = results;
    }
});

console.log(this.users);

data from DB are not probably loaded yet into users variable when you are trying to log it into console. You can check it out if you do your console.log operation within the query, for example:

client.query("SELECT * FROM users", function (error, results, fields) {
    if (error) {
        //
    }
    if (results.length  > 0) {
        console.log(results);
    }
});

To pass the result into a variable when the operation is finished you can wrap your client DB call into a function with callback parameter and set your variable when the callback is invoked, for example:

function query(sql, callback) {
    client.query(sql, function (error, results, fields) {
        if (error) {
            //
        }
        if (results.length  > 0) {
            callback(results);
        }
    });
}

query("SELECT * FROM users", function(results) {
    self.users = results;
    console.log(self.users);
});

Above code is just a concept.

like image 143
yojimbo87 Avatar answered Sep 19 '22 07:09

yojimbo87