node-mysql connection.query() returns undefined

freakimkaefig picture freakimkaefig · Aug 3, 2012 · Viewed 8.7k times · Source

I'm using a node ws server built on einaros/ws. That server has to send queries to a database. For that i'm using felixge/node-mysql.

When a user connects to the server, it should be checked if the client still exists in the database.

Here is the interesting piece of code:

console.log("client-liste ist leer");
var query = "SELECT name FROM spieler WHERE name='"+id+"' AND passwort='"+passwort+"'";
var result = queryToDatabase(query);
console.log(getTime() + "DB-Result Abfrage: " + result);

And the Code where the query is done:

var mysql = require('mysql');
var mysqlConnection = mysql.createConnection({
    host: dbHost,
    user: dbUser,
    password: dbPassword,
});

function queryToDatabase(anfrage) {
    mysqlConnection.connect();

mysqlConnection.query("USE " + db, function(err, rows, fields) {
    if (err) throw err;
});

mysqlConnection.query(anfrage, function(err, rows, fields) {
        if (err) throw err;
        console.log("rows as String - " + JSON.stringify(rows));
        return rows;

    });

    mysqlConnection.end();
}

The Logs in the console are:

client-liste ist leer
3.8.2012 - 15:29:0 - DB-Result Abfrage: undefined
rows as String - [{"name":"lukas"}]



Does anyone understand, why the function returns undefined? I also tried to wait for Database-Connection to finish with a simple setTimout, but nothing changed!

Answer

ebohlman picture ebohlman · Aug 3, 2012

You can't return a value from an asynchronous callback like the one used by query. You need to rewrite queryToDatabase so it takes a callback as its second argument and calls it with rows when the query is successful. Then your main code needs to look like:

queryToDatabase(query, function(result) {
     console.log(getTime() + "DB-Result Abfrage: " + result);
   });

In reality, all your code that depends on the query result will need to go into that callback.

In practice, you'd want the callback to take two arguments: an error status and a result, with the error status being null if the query was successful.