1

I'm trying to use a SELECT query on my SQL database using node.js, the SELECT query below should work but doesn't. This is weird because I think this should work but it doesn't even enter the client.query function. I also copied my INSERT query which is actually working to show you my connection to the database works fine.

What am I doing wrong in the SELECT query?

CreateConnection

var mysql = require('mysql');
var client = mysql.createConnection({
    host: '***',
    user: '***',
    password: '***',
    database: '***'
});

SELECT Query (Not working)

    function query(sql){
      var returnvalue = "tempVal";
      client.connect();
      client.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
        returnvalue = "doens't even enter function";
        if (err) throw err;

        returnvalue = rows[0].solution;
      });
      client.end();    
      return returnvalue;
    }

INSERT Query (Is working)

function query(sql){
  client.connect();
  client.query('INSERT INTO users (username) VALUES("foo")');
  client.end();
}
1
  • Welcome to the wonderful world of async! You can't do that. Commented Jul 3, 2013 at 14:08

1 Answer 1

1

As .query() is an asynchronous method, you won't be able to return the value as the callback will be called after the return is evaluated.

You'll have to continue the callback pattern:

function query(sql, callback) {
    client.connect();
    client.query(sql, function (err, rows, fields) {
        if (err) {
            callback(err);
        else
            callback(null, rows, fields);
    });

    client.end();
}

Correction: Seems client.end() will allow current queries to finish before the connection actually closes.

Closing the connection is done using end() which makes sure all remaining queries are executed before sending a quit packet to the mysql server.

Though, calling .end() inside the callback is commonplace for many APIs as they will cut-off any pending actions.

Sign up to request clarification or add additional context in comments.

Comments

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.