gpt4 book ai didi

javascript - 无法使用 mysql 和 Node js 返回选择查询值

转载 作者:可可西里 更新时间:2023-11-01 06:51:03 26 4
gpt4 key购买 nike

我是 node js 的新手,现在我正在尝试使用 node 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 始终未定义。我知道这是异步调用。谁能告诉我如何为这个变量设置值。

谢谢迪帕克

最佳答案

由于数据库查询是异步操作,因此在您调用 console.log(retValue) 时您的变量 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

关于javascript - 无法使用 mysql 和 Node js 返回选择查询值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29913206/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com