0

I want to pass a result from mysql query to the level above...

I have this module: mySQLconnect.js:

var connection = require('mysql').createConnection({
  host : 'localhost',
  user : 'admin',
  password : ''
});

exports.querySelect = querySelect;

function querySelect(query){
    var result = connection.query(query, function(err, rows){
                           return (rows[0]);
                 });
    return result;
}

and when I call this function from outside, let's say from app.js:

var DBconnector = require('mySQLconnect');    
var result = DBconnector.querySelectUser("SELECT * FROM TB_USERS");

but the result I get is something else - it's an object from mysql.js module that's been received from:

connection.query(query, function(err, rows)

it has: _resultSet =null, and unreachable _results =[Array]

so it's no good...

I checked in node-mysql website, but didn't find what's connection.query returns.

any ideas how can I pass the result?

1 Answer 1

1

You are wrapping an asynchronous call to the DB with a procedural function – a common mistake for nodejs beginners coming from a procedural language like PHP.

You can simplify your mySQLconnect.js module to the following:

var connection = require('mysql').createConnection({
  host : 'localhost',
  user : 'admin',
  password : ''
});

exports.querySelect = connection.query;

And then consume it thusly:

var DBconnector = require('mySQLconnect');
DBconnector.querySelect("SELECT * FROM TB_USERS", function (err, rows) {
  console.log(err || rows);
});

I would read up on callbacks, anonymous functions, and asynchronous flow patterns to help you wrap your head around this new style of coding. Good luck!

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.