我是节点js中的新手,现在我正在尝试使用节点js在mysql中设置select查询的返回值....我正在使用node-mysql包...
示例代码
var mysql = require('mysql');
var connection = mysql.createConnection({
host : "localhost",
user : "root",
password: "root123",
database: "testdb"
});
var retValue = undefined;
var query = connection.query('SELECT * FROM tblData;');
query
.on('error', function(err) {
// Handle error, an 'end' event will be emitted after this as well
})
.on('fields', function(fields) {
// the field packets for the rows to follow
})
.on('result', function(row) {
// Pausing the connnection is useful if your processing involves I/O
connection.pause();
processRow(row, function() {
retValue = row;
});
})
.on('end', function(row) {
});
connection.end();
function processRow(rows)
{
retValue = rows;
}
console.log(retValue);
retValue
始终未定义。我知道这是异步调用。有人告诉我如何设置这个变量的值。
由于 迪帕克
答案 0 :(得分:1)
由于数据库查询是异步操作,因此在您调用retValue
时尚未设置变量console.log(retValue)
。
var retValue;
var query = connection.query('SELECT * FROM tblData;');
query
.on('error', function(err) {
// Handle error, an 'end' event will be emitted after this as well
})
.on('fields', function(fields) {
// the field packets for the rows to follow
})
.on('result', function(row) {
// Pausing the connnection is useful if your processing involves I/O
connection.pause();
processRow(row);
console.log(retValue); //retValue is now set
})
.on('end', function(row) {
});
connection.end();
function processRow(rows)
{
retValue = rows;
}
console.log(retValue); // undefined, retValue has not been set yet
答案 1 :(得分:0)
retvalue只在范围内可用,即你输入结果。所以你可以做类似的事情来记录你的结果:
var connection = mysql.createConnection({
host : "localhost",
user : "root",
password: "root123",
database: "testdb"
});
var retValue = undefined;
var query = connection.query('SELECT * FROM tblData;', function(err, results, fields) {
console.log(results);
// Here continue logic you needed with results from table
});
答案 2 :(得分:0)
将console.log
移到function processRow(rows)
内,使其看起来像
function processRow(rows)
{
retValue = rows;
console.log(retValue);
}
也改变了
processRow(row, function() {
retValue = row;
});
要
processRow(row);
第二个参数未使用。
答案 3 :(得分:0)
我无法从范围中得到结果...我想分配并返回这样的值
fucntion()getResults { ... ... var retValue = undefined;
var query = connection.query(' SELECT * FROM tblData;',function(err,results,fields){ retValue =结果; });
返回retValue };
var ret = getResults(); 的console.log(RET);