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();
}
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.