Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can't return a select query value using mysql and node js

I am new in node js, Now I am trying to set a return value of select query in mysql using node js....I am using node-mysql package...

example code

var mysql =  require('mysql');
var connection =  mysql.createConnection({
    host : "localhost",
    user : "root",
    password: "root123",
    database: "testdb"
});

var retValue = undefined;

var query = connection.query('SELECT * FROM tblData;');
query
    .on('error', function(err) {
        // Handle error, an 'end' event will be emitted after this as well
    })
    .on('fields', function(fields) {
        // the field packets for the rows to follow
    })
    .on('result', function(row) {
        // Pausing the connnection is useful if your processing involves I/O
        connection.pause();
        processRow(row, function() {
            retValue = row;
        });
    })
    .on('end', function(row) {

    });

    connection.end();

    function processRow(rows)
    {
        retValue = rows;
    }

    console.log(retValue);

retValue is always undefined. I know it is asynchronous call. anyone tell me how to set value for this variable.

Thanks Deepak

like image 890
Deepak Samuel Avatar asked Apr 28 '15 07:04

Deepak Samuel


People also ask

Can you use MySQL with node js?

Once you have MySQL up and running on your computer, you can access it by using Node. js. To access a MySQL database with Node. js, you need a MySQL driver.


1 Answers

Since database query is an asynchronous opreation, your variable retValue has not been set yet at the time you call console.log(retValue).

var retValue;

var query = connection.query('SELECT * FROM tblData;');
query
    .on('error', function(err) {
        // Handle error, an 'end' event will be emitted after this as well
    })
    .on('fields', function(fields) {
        // the field packets for the rows to follow
    })
    .on('result', function(row) {
        // Pausing the connnection is useful if your processing involves I/O
        connection.pause();
        processRow(row);
        console.log(retValue); //retValue is now set
    })
    .on('end', function(row) {

    });

    connection.end();

    function processRow(rows)
    {
        retValue = rows;
    }

    console.log(retValue); // undefined, retValue has not been set yet
like image 156
Lewis Avatar answered Oct 15 '22 00:10

Lewis