nodejs 取值 mysql,如何使用mysql包从nodejs获取结果?

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 ??

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值