0

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'");
}
2
  • For some reason the var is not chainging it's value @amrswalha Commented Jul 8, 2013 at 13:56
  • what mysql package for node are you using first ? Commented Jul 8, 2013 at 13:59

1 Answer 1

2

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);}
Sign up to request clarification or add additional context in comments.

6 Comments

the cmd if it's inside the callback it return null value @luksch
can you log to the console how your SQL query looks like? also, log the result row to the console
SELECT value As data from cmd where cmd='textbox'
And what does the SELECT value As data from cmd where cmd='textbox'; return when you do it directly within the mysql console?
It return result but the value of the cmd does not change for some reason
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.