我有一个带有Express和mysql的NodeJS。我已经放了一个Generic sql函数,所以我多次调用它:
exports.selectCommand=function(table,cols,cond){
var connection = mysql.createConnection({
host : hostname,
database: databasename,
user : username
});
try{
connection.query("SELECT "+cols+" As data from "+table+" where "+cond+" ", function(err, rows, fields) {
if (err) return "sorry, an error accoured. Please try again later";
if(rows.length!=0){
cmd = rows[0].data.toString();
}
});
}catch (e){console.log(e.message);}
connection.end();
return cmd; };
我发送了查询,但问题是它返回我发送的第一个查询。
我已将上述功能放在另一个文件中,我称之为:
var db=require('./db.js');
..........
exports.psModel=function(){
var cmddata="";
cmddata=db.selectCommand("cmd","value","cmd='textbox'");
}
答案 0 :(得分:2)
您的return cmd
可能在处理查询之前返回。该调用是异步的。尝试将return语句放在回调中(以及连接端)。像这样:
try{
connection.query("SELECT "+cols+" As data from "+table+" where "+cond+" ",
function(err, rows, fields) {
connection.end();
if (err) return "sorry, an error occurred. Please try again later";
if(rows.length!=0){
cmd = rows[0].data.toString();
return cmd;
}
});
}catch (e){console.log(e.message);}