Reputation: 334
I have a NodeJS with Express and mysql. I have put an Generic sql function so I call it for multiple times:
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; };
I send the query thorugh it but the problem it return the first query I send it.
I've put the above function in another file and I call it:
var db=require('./db.js');
..........
exports.psModel=function(){
var cmddata="";
cmddata=db.selectCommand("cmd","value","cmd='textbox'");
}
Upvotes: 0
Views: 4643
Reputation: 11712
your return cmd
returns probably before the query is processed. The call is asynchronous. Try to place the return statement within the callback (and the connection end as well). Something like this:
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);}
Upvotes: 2