wig on the run
wig on the run

Reputation: 3

Get data from MySQL query for use in nodejs

Trying to query my database and each time I do, it runs all the queries at the end instead of when I need them in nodejs.

var mysql = require('mysql');

var con = mysql.createConnection({
  host: database.host,
  user: database.user,
  password: database.password,
  database: database.database
});

The connection data I am pulling from a json file.

function getSymbol(id){
var s = "";
con.query("SELECT * FROM Symbol WHERE PlayerID = '" + id + "'", function (err, result, fields) {
    if (err) throw err;
    console.log(result);
    if (result.length < 1) {
        console.log(result);
        s = result[0].Symbol;
    }
    else {
        s = "!";
    }
});
console.log(s);
return s;

}

It all runs at the end of the program wondering if there is a fix or if I should switch to python (seriously considering rewriting all of it at this point).

Upvotes: 0

Views: 160

Answers (2)

Vetras
Vetras

Reputation: 1999

As mentioned, the method is NOT sync. Your result will be on the callback you pass.

con.query(sql, function (err, result) {
    if (err) throw err;
    console.log("The Data: " + result);
});

More Info: https://www.w3schools.com/nodejs/nodejs_mysql.asp

Moreover, you need to connect first with con.connect( <callback-here> ).

The best way to work with this is to avoid the callbacks for async/wait syntax.

Upvotes: 0

GRS
GRS

Reputation: 1957

The problem is what you have written comes under NIO and it wont wait for executing the next statement unless you ask it to. Try the below code:

async function getSymbol(id){
   var s = "";
   try {
    let result = await con.query("SELECT * FROM Symbol WHERE PlayerID = '" + id + "'")
    if (result.length < 1) {
        console.log(result);
        s = result[0].Symbol;
    }
    else {
        s = "!";
    }
   }catch(error){
        console.log(error);
        throw new error;
   }
    console.log(s);
   return s;
 }

Note: I have used async/await. You can also use Promises

Upvotes: 1

Related Questions